JS.Node Flashcards
What is a common error made when storing data as JSON ?
stringifying the data more than once before storage or not stringifying it at all.
what does array.filter() do?
filters an existing array and returns a new array that contains only the filtered values.
what does array.foreach() do?
Much like a for loop, it loops through each item in an array and performs a specified opperation on each item.
What does array.map() do?
Performs an opperation on each value within an array and returns a new array that contains the new mapped values.
What does array.reduce() do?
reduces the values in a given array to a single value.
What does it mean when we say that node uses “non-blocking I/O”?
It means that Node is asynchronous.
What are the two most common JSON commands?
JSON.stringify() and JSON.parse()
What does JSON.stringify do?
turns an object into a JSON object by adding double quotes to the keys and values in objects.
What does JSON.parse() do?
turns JSON objects into objects by removing the double quotes from the keys in an object.
Which module is used to work with files in node?
fs
Which module is used to provide colourful feedback in the console?
chalk
How does the V8 engine works
Node itself is written in C++ and the V8 engine is embedded into it. When writing javascript. The javascript and it’s c++ bindings are passed into the V8 engine which converts it to machine language which can be run on a machine like a computer or a server.
The javascript engine used by Chrome
V8
The javascript engine used by Edge
Chakra
The javascript engine used by Firefox
Spidermonkey
The javascript engine used by Edge
Javascriptcore
What is a javascript engine?
A program that compiles javascript down to machine language
What is the difference between an AOT and JIT compiler?
AOT (ahead of time) compilers, will compile the entire program into machine code ahead of time.
JIT (Just in time) compilers used a combination of interpretation and compilation and will compile blocks of code just before it is neede.
JIT is slower than AOT but it makes it easier to debug and maintain code.
The V8 engine is multi-threaded. What are the 4 main threads and what are there functions?
- Main thread: Fetch - compile -execute
- Compiler thread: Codegen(ignition): converts to
machine code Crankshaft(turbofan): optimizes hot
code - Profiler thread: Monitors code and finds “hot” sections
- Garbage collection thread: Garbage collection
How does crankshaft optimize code?
1. inlining: All the function in the "hot" path are replaced by the actual code from the function to improve performance 2. Hidden classes: The compiler generates hidden classes that maintains the pointers to every object property in a class structure so that it need not be looked up everytime 3. inline caching: A cache of the object type that is most likely to be passed to a function is maintained so that unnecessary lookups are avoided
what is a “method”?
Methods are functions defined as a propertie of an object or class. methods are executed using the dot notation.
Why are arrow functions not well suited for use as methods in an object?
Because arrow functions do not bind their own “this” value, instead they access the “this” value of the context they were created in. This can make it difficult to access properties within objects. Instead it would be better to use an anonymous function which binds its own “this” value
What are arrow functions best used for?
callback functions
What should we use in the place of array.filter() when looking for a single item in a large array? Why?
Array.find()
Array.filter() will look through each item in a list one at a time. It will continue to do so even if the item we are looking for has been found.
Example. In a list of 1000 items, if the item we are looking for is at index 89, it will continue to look through the remaining 911 items before stopping.
Array.find() will stop after it finds the first instance of the desired item.
Array.find()
Looks for item in an array an returns the item (not new array) when found.
Returns “undefined” when nothing is found
How can I use chrome as a debugging tool?
add debugger to script
run “node inspect app.js commands” in terminal
navigate to chrome://inspect in the chrome browser
add folders to project
press esc to toggle console
press run top right hand corner
look at values in the right hand pane.
What are the 6 catagories of errors in javascript?
EvalError: Raised when the eval() functions is used in an incorrect manner.
RangeError: Raised when a numeric variable exceeds its allowed range.
ReferenceError: Raised when an invalid reference is used. Like when you use a variable that has not been declared
SyntaxError: Raised when a syntax error occurs while parsing JavaScript code.
TypeError: Raised when the type of a variable is not as expected. Like when you call .toUpperCase() on an integer
URIError: Raised when the encodeURI() or decodeURI() functions are used in an incorrect manner.
Javascript generates an error object when an error occurs. Which two propperties does it contain?
name
message
What is a stack trace?
A stack trace is a list of the functions, in order, that lead to a given point in a software program.A stack trace is essentially a breadcrumb trail for your software.It helps us understand the steps that lead to the error.
What is the biggest problem with anonymous functions?
They make it difficult to debug as they show up in the stack trace as anonymous.
console.trace()
A command that can be placed inside a function which then generates a stack trace for that funciton in the console or terminal.
Format of a stack trace
Error name function name, file, line number, column number
Which async function can be used to time the execution of a function?
setTimeout(callback, time in milliseconds)
Call stack
a call stack is a stack data structure which is based on the LIFO or last in first out principle. It uses four opperations namely push (to add data), pop (to remove data), peek (to return the value of the top item), isEmpty (returns true if stack is empty). Stacks emulate real life stacks like a stack of books or a can of tennis balls.
Whe a script runs, it wraps all of the code in the main() function. The main function gets pusched onto the call stack and executes, then any function called by main gets pushed onto the call stack on top of main. when the function has finished running it is poped of the call stack. and right at the end of the script the main funciton is popped of the stack.
Callback que
a que used by node to keep track of callback functions that are waiting to run.
Event loop
Adds functions waiting in the call back cue to the call stack when the stack is empty.
Explain what happens in the background when running asyncronous scripts?
Function gets pushed onto the callstack, the async event gets registered with the node api, when it is ready or complete it is moved to the callback cue where it waits for the event loop to add it to the call stack as soon as the call stack is empty. Once it is in the call stack it get executed.
How to initialize a new project as an NPM project?
run “npm init -y” in the root of the folder
package.json file
holds the metadata and information about dependencies and project configuration. It is generated automatically as soon as a project is initialized using npm init
Which npm module can be used ot make http requests?
request
simplest way to make an http request using request?
request({url:url,json:true},(error,response)=>{
console.log(response)
});
Which chrome extension presents json data in a more readable format?
JSON formatter
What are query strings?
a query string is the part of a uniform resource locator (URL) which assigns values to specified parameters. The query string commonly includes fields added to a base URL
query string format base_url?key=value&key=value
Which api provides geocoding or location based information?
Mapbox.
How can errors be handled when using the npm request module to make http requests?
if(error){ console.log("cannot connect) }else if(response.body.error){ console.log("cannot find info") }else{ console.log(response.body) }
What is defensive programming?
Anticipating possible errors and pre-emptively writing code that solves the anticipated problem
A common example is the try/catch statements
What is a call back function?
A callback is a function that is to be executed after another function has finished executing
Functions that do this are called higher-order functions.
Any function that is passed as an argument is called a callback function.
What is a higher order function?
Any function that calls another function or that takes another funciton as an argument
What is a common convention used for callback functions?
someFunction(arg,(error,data)=>{
})
which function helps to parse user input into a valid URI component?
encodeURIComponent()
In which folder should code be placed that make api calls or HTTP requests?
utils
What is callback chaining?
chaining together a number of functions via callbacks while passing arguments (data) between them.
What is callback hell?
When so many functions have been chained together that it becomes unreadable and difficult to understand.
What is object destructuring?
A method that extracts values from an object
const book = { label:"To the moon and back", price:56, author:"Ryan holiday" }
const {label, price} = book
How to rename a property during object destructuring?
currentName:newName
const book = { label:"To the moon and back", price:56, author:"Ryan holiday" }
const {label:title, price:cost} = book
How to set defualt values for properties when they don’t exist in an object during destructuring?
Using the assignment operator
const book = { label:"To the moon and back", price:56, author:"Ryan holiday" }
const {title, cost = 100} = book
How to destructure an object passed in as an argument into a function?
by using curly braces.
const book = { label:"To the moon and back", price:56, author:"Ryan holiday" }
function inventory(type, {label, price, author}){ some code here }
Which core modules are used ot make http requests
http and https
How to make an HTTP request using the https core module?
const https = require(‘https’);
const request = https.request(url,(response)=>{ let data = '';
//event listener that adds the chunks of data returned from the server. Data is returned as a series of buffers which needs to be converted to a string response.on('data', (chunk)=>{ data = data + chunk.toString()
});
//runs when response is complete converting the string to an object response.on('end',(chunk)=>{ const body = JSON.parse(data); console.log(body)
})
});
//Event listener that handles errors request.on('error', (error)=>{ console.log('An error ', error) });
//This code snippet tells the request to run, it won't run without it. request.end();
Which npm module is commonly used to create servers?
express
directory structure for node projects
lib/ is intended for code that can run as-is
src/ is intended for code that needs to be manipulated before it can be used
build/ is for any scripts or tooling needed to build your project
dist/ is for compiled modules that can be used with other systems.
bin/ is for any executable scripts, or compiled binaries used with, or built from your module.
test/ is for all of your project/module’s test scripts
unit/ is a sub-directory for unit tests
integration/ is a sub-directory for integration tests
env/ is for any environment that’s needed for testing
What is the src directory intended for?
is intended for code that needs to be manipulated before it can be used
What is the most basic server setup using express?
const express = require(‘express’); //import express
const server = express(); //create a server
server.get(‘’,(req,res)=>{ //handle request for homepage
res.send(‘Hello world’) //sends a response
});
const port = 3000; //sets the port to listen on
server.listen(port,()=>{ //starts the server
console.log(‘Server is up and running on port ‘ + port)
});
What is the simplest way to handle a request to the express server?
//by setting up a route
server.get(‘’,(req,res)=>{
res.send(‘Hello world!’)
})
Which variables can be used in node to access the absolute path of a file and a directory
__dirname
__filename
Which core NODE module can be used to manipulate or create path strings
path
Which comman allows us to move up one directory?
../
Which command allows us to move up two directories?
../../
Which command allows us to access files in the same directory?
./
What is the purpose of the public folder in node.js?
To serve up static pages such as html, css and javascript
How to setup public folder in express server
const publicDirectoryPath = path.join(__dirname, ‘../public’)
server.use(express.static(publicDirectoryPath))
Where are css files stored on a server?
inside the css folder within the public directory
Where are html files stored on a server?
within the public directory
Where are js scripts stored on a server?
inside the js folder within the public directory
How to link stylesheet to html file
How to link javascript to html file
Where are images stored on a server?
in the img folder within the public folder
Which npm module allows for templating?
hbs and handlebars
What are template engines?
A template engine enables you to generate dynamic content in express. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
How do we setup a template engine to serve dynamic content in express?
//install handlebars module npm i hbs
//set up view engine server.set('view engine','hbs')
//create directory for views in the root directory
How to render dynamic content to a browser using express.
//using a route //use res.render() instead of res.send() // render takes two arguments // the file to be rendered's name // an object with the dynamic content.
server.get(‘’,(req,res)=>{
res.render(‘filename’, {property:value})
});
Setting a path for the views directory when working with dynamic content in express?
const viewsDirectoryPath = path.join(\_\_dirname,"../templates"); app.set('views',viewsDirectoryPath);
How to structure templates directory?
root => templates => views, partials
server.set(‘views’, path)
When working with the hbs how can we register the partials directory?
hbs.registerPartials(partialsDirectoryPath);
What file extension does handlebar files use?
hbs
How to add a partial to a handlebars file?
{{>filename}}
Which character is used when setting up 404 pages in node express?
The wild card *
Why does the route handler for 404 need to be last?
Node looks through each route handler in the order they are written. Node will ignore all route handlers after the wild card.
What are the steps in setting up a basic servier using express?
- import modules
- create server
- set public directory
- create template machine
- set views directory
- register and set partials directory
- Set up route handlers
- Set up 404 route handler
- Start server
How to access queries in the route handlers in express?
req.query
How to handle query errors in express?
if(!req.query.searchterm){
return res.send({
error:”You must provide a search term”
})
How to make client side http requests or api calls?
fetch(url).then((response)=>{ response.json().then((data)=>{ if(data.error){ console.log(data.error) }else{ console.log(data) } }) })
How to get the information from an html form in javascript?
//save the form element const weatherForm = document.querySelector('form');
//Save the input element const search = document.querySelector("input")
//Add an event listener weatherForm.addEventListener('submit',(e)=>{ e.preventDefault() //prevent default const location = search.value() //get the value console.log('Testing form') });
How to prevent a form from refreshing the webpage after submission?
//use e.preventDefualt() to prevent default behaviour
weatherForm.addEventListener(‘submit’,(e)=>{
e.preventDefault()
console.log(‘Testing form’)
Why is it better to make http requests from the server and not from the client side?
Because most browsers or websites will block cross-origen requests due to the specter vulnerabillty that would allow one access to a websites files and and content.
Which folder don’t you want git to track?
node_modules
How to recreate the node_modules folder?
npm install
How to get git to not track the node_module folder?
Add a .gitignore file to the root directory and write node_modules/ in the file
How to run a script from the package.json file?
npm run scriptname
Why should global modules be avoided?
Because, when other developers download the project onto their machine, the global modules are not included, which means that the program wont run as expected or at all.
How to uninstall a global module?
npm uninstall -g moduleName
What does –save-dev do?
npm i module –save-dev installs a package as a dev dependency
how are dev dependencies different from regular dependencies?
dev dependencies are not intalled in a production environment, only in a development environment
When nodemon is installed locally, can we still access it using the nodemon command in the terminal?
No. The command only works when it is installed globally. In order to run it locally, you have to create a dev script
REST API: What does REST stand for?
Representational State Transfer
REST API: CRUD methods
Create: POST
Read: GET
Update: PATCH
Delete: DELETE
REST API: Structure of http request
- Request line: Method, Path, protocol
- Multiple Request headers: Key/Value pairs
a. ) Accept: application/json -tells the api what kind of data to return
b. ) Connection: Keep-Alive -tells the api to keep the connection open as more requests are likely to be made.
c. )Authorization: Bearer ey34Jdetc. -contain authorization keys - Request body that contains Data provded as JSON
REST API: Structure of http response
- Status line: Protocol, status code, text representation of status code
- Response Headers: Date, server, content type
- Body: contains JSON data
A list of commonly installed npm packages
nodemon express request mongodb mongoose validator hbs bcryptjs jsonwebtoken multer sharp @sendgrid/mail env-cmd jest supertest
REST API: How to configure the server to make incoming JSON data available as an object we can use
server.use(express.json());
this will make json available as an object accessibel on req.body
Status codes
100: informational
200: success
300: redirection
400: Client Error codes
500: Server error codes
Status codes
httpstatuses.com
100: informational
200: success
300: redirection
400: Client Error codes
500: Server error codes
REST API: How to connect or access mongodb database from the server?
- import the mongoose client
require(‘./db/mongoose.js’)
2. import the models const User = require('./db/models/user.js')
- instantiate an instance of the model in to be used by the routes
REST API: Handling POST requests
//Post request creating a new user
server.post(“/users”,(req,res)=>{
const user = new User(req.body); user.save().then(()=>{ res.send(user); }).catch((error)=>{ res.status(400).send(error) }) });
REST API: What is the default status code returned from express?
200
REST API: Handling GET or read requests
//in this example the Task model is not instantiate, instead .find() is called directly on the model itself
server.get("/tasks",(req,res)=>{ Task.find({}).then((tasks)=>{ res.send(tasks) }).catch((error)=>{ res.status(500).send(error) }) });
//in retrieving a specific document, an id is added to the end of the url using :id, which is then accessed using req.params.id.
server.get("/tasks/:id",(req,res)=>{ const id = req.params.id; Task.findById(id).then((task)=>{ if(!task){ return res.status(404).send() } res.send(task); }).catch((error)=>{ res.status(500).send(error) }) });
Difference between .every() and .foreach()
An important difference with .every() is that the test function may not always be called for every element in the array. Once the testing function returns false for any element, no more array elements are iterated. Therefore, the testing function should usually have no side effects.
.forEach() returns nothing - It iterates the Array performing a given action for each item in the Array.
Which algorithm is used for encrypting user passwords?
Bcrypt
How to hash a password with bcrypt?
const password = 'Red12345!' const hashedPassword = await bcrypt.hash(password,8);
Can a hashed password be decrypted?
No, it is one way
If a hased password can’t be dycrypted, how can we compare a users password with the hashed one stored in the system?
const isMatch = await bcrypt.compare(userPassword, storedHashPassword)
What is mongoose middleware?
Allows for the customization of mongoose models
Which two mongoose methods can overide middleware?
.findById
.update
Which npm package can be used to generate tokens?
jasonwebtoken
What are the different parts of a JWT?
it has 3 parts: Header, Body,
The Header is a base 64 encoded json string that contains meta information about the type of token and the algorithem used ot generate it.
What are the different parts of a JWT?
it has 3 parts: Header, Body, signiture
The Header is a base 64 encoded json string that contains meta information about the type of token and the algorithem used ot generate it.
The Body is a base 64 encoded string that contains the payload and a timestamp
The signitureis a base 64 encoded string that contains the signiture used to verify the token
How to create a web token?
const token = jwt.sign({_id:’abc123’}, ‘secretKey’);
How to verify a toke?
const data = jwt.verify(token,’secretKey’);
returns a payload object if verified, otherwise it throws an error
Mongoose: How to define methods to be called on the model?
userSchema.statics.methodName(){
}
Mongoose: How to define methods to be called on a model instance?
userSchema.methods.methodName(){}
What is express middleware?
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
How to setup express middleware?
//middleware needs to be created above the route handlers for it to work
server.use((req,res,next)=>{ if(req.method === 'GET'){ res.send('GET requests are disabled') } else { next() } });
How is authentication tokens sent to the route handlers or server
placed in the header
Key: Authorization
Value: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTk5NjI0M2FiZTA3ZTBkNDAzYjE5YzUiLCJpYXQiOjE1ODcxNzk5OTN9.eGfK8IoVIbbpyH2SxTR9_Liw7YTGDisVbc5MDMdaqFE
How to populate a model with fields from a related model?
//test const Task = require('./db/models/task'); const User = require('./db/models/user');
const main = async ()=>{
const user = await User.findById(‘5e99a4a5e97c45531011fe95’);
await user.populate(‘tasks’).execPopulate();
console.log(user.tasks)
}
main();
How to add a time stamp to a data model?
when defining the modelSchema pass the following object in as the second argument
{timestamps:true}
Which npm library allows you to upload media files to the data base?
multer
Multer: How to limit file size and filter for specific file types?
const upload = multer({ dest:"avatar", limits:{ fileSize:1000000 }, fileFilter(req,file,cb){ if(!file.originalname.endsWith('.pdf')){ cb(new Error('Please upload a pdf!')) }
cb(undefined,true) } });
router.post(‘/users/uploads/avatar’,upload.single(‘avatar’), (req,res)=>{
res.send()
});
Multer: How to use regex to filter for specific file types
const upload = multer({ dest:"avatar", limits:{ fileSize:1000000 }, fileFilter(req,file,cb){ if(!file.originalname.match(/\.(jpg|jpeg|png)$/)){ return cb(new Error('Please upload a word document!')) }
cb(undefined,true) } });
Multer: How to handle errors, when client uploads the wrong file type?
router.post(‘/users/uploads/avatar’,upload.single(‘avatar’), (req,res)=>{
res.send()
},(error,req,res,next)=>{
res.status(400).send({error:error.message})
});
How to set an image in html with binary code instead of a file?
<img></img>
When returning a file to a client, what needs to be set before it is sent?
Need to set the header
res.set(‘content-type’,’image/jpg’)
or
res.set(‘content-type’,’application/json’)
Which module helps to reformat an image?
sharp
How to reformat an image using sharp?
const buffer = await sharp(req.file.buffer).resize({width:250, height:250}).png().toBuffer(); req.user.avatar = buffer;
How to setup environment variables?
- install npm i env-cmd
- Create a dev.env file
- Setup variables in the file
- access variables in relevant locations using process.env.ENV_NAME
- Set the dev script to “env-cmd -f ./dev.env nodemone src/index.js”