JS.Node Flashcards

1
Q

What is a common error made when storing data as JSON ?

A

stringifying the data more than once before storage or not stringifying it at all.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what does array.filter() do?

A

filters an existing array and returns a new array that contains only the filtered values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what does array.foreach() do?

A

Much like a for loop, it loops through each item in an array and performs a specified opperation on each item.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does array.map() do?

A

Performs an opperation on each value within an array and returns a new array that contains the new mapped values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does array.reduce() do?

A

reduces the values in a given array to a single value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does it mean when we say that node uses “non-blocking I/O”?

A

It means that Node is asynchronous.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the two most common JSON commands?

A

JSON.stringify() and JSON.parse()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does JSON.stringify do?

A

turns an object into a JSON object by adding double quotes to the keys and values in objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does JSON.parse() do?

A

turns JSON objects into objects by removing the double quotes from the keys in an object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which module is used to work with files in node?

A

fs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Which module is used to provide colourful feedback in the console?

A

chalk

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How does the V8 engine works

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

The javascript engine used by Chrome

A

V8

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

The javascript engine used by Edge

A

Chakra

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

The javascript engine used by Firefox

A

Spidermonkey

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

The javascript engine used by Edge

A

Javascriptcore

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a javascript engine?

A

A program that compiles javascript down to machine language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the difference between an AOT and JIT compiler?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

The V8 engine is multi-threaded. What are the 4 main threads and what are there functions?

A
  1. Main thread: Fetch - compile -execute
  2. Compiler thread: Codegen(ignition): converts to
    machine code Crankshaft(turbofan): optimizes hot
    code
  3. Profiler thread: Monitors code and finds “hot” sections
  4. Garbage collection thread: Garbage collection
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How does crankshaft optimize code?

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

what is a “method”?

A

Methods are functions defined as a propertie of an object or class. methods are executed using the dot notation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Why are arrow functions not well suited for use as methods in an object?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are arrow functions best used for?

A

callback functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What should we use in the place of array.filter() when looking for a single item in a large array? Why?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Array.find()
Looks for item in an array an returns the item (not new array) when found. Returns "undefined" when nothing is found
26
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.
27
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.
28
Javascript generates an error object when an error occurs. Which two propperties does it contain?
name | message
29
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.
30
What is the biggest problem with anonymous functions?
They make it difficult to debug as they show up in the stack trace as anonymous.
31
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.
32
Format of a stack trace
``` Error name function name, file, line number, column number ```
33
Which async function can be used to time the execution of a function?
setTimeout(callback, time in milliseconds)
34
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.
35
Callback que
a que used by node to keep track of callback functions that are waiting to run.
36
Event loop
Adds functions waiting in the call back cue to the call stack when the stack is empty.
37
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.
38
How to initialize a new project as an NPM project?
run "npm init -y" in the root of the folder
39
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
40
Which npm module can be used ot make http requests?
request
41
simplest way to make an http request using request?
request({url:url,json:true},(error,response)=>{ console.log(response) });
42
Which chrome extension presents json data in a more readable format?
JSON formatter
43
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
44
Which api provides geocoding or location based information?
Mapbox.
45
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) } ```
46
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
47
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.
48
What is a higher order function?
Any function that calls another function or that takes another funciton as an argument
49
What is a common convention used for callback functions?
someFunction(arg,(error,data)=>{ })
50
which function helps to parse user input into a valid URI component?
encodeURIComponent()
51
In which folder should code be placed that make api calls or HTTP requests?
utils
52
What is callback chaining?
chaining together a number of functions via callbacks while passing arguments (data) between them.
53
What is callback hell?
When so many functions have been chained together that it becomes unreadable and difficult to understand.
54
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
55
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
56
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
57
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 } ```
58
Which core modules are used ot make http requests
http and https
59
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(); ```
60
Which npm module is commonly used to create servers?
express
61
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
62
What is the src directory intended for?
is intended for code that needs to be manipulated before it can be used
63
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) });
64
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!') })
65
Which variables can be used in node to access the absolute path of a file and a directory
__dirname __filename
66
Which core NODE module can be used to manipulate or create path strings
path
67
Which comman allows us to move up one directory?
../
68
Which command allows us to move up two directories?
../../
69
Which command allows us to access files in the same directory?
./
70
What is the purpose of the public folder in node.js?
To serve up static pages such as html, css and javascript
71
How to setup public folder in express server
const publicDirectoryPath = path.join(__dirname, '../public') server.use(express.static(publicDirectoryPath))
72
Where are css files stored on a server?
inside the css folder within the public directory
73
Where are html files stored on a server?
within the public directory
74
Where are js scripts stored on a server?
inside the js folder within the public directory
75
How to link stylesheet to html file
76
How to link javascript to html file
77
Where are images stored on a server?
in the img folder within the public folder
78
Which npm module allows for templating?
hbs and handlebars
79
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.
80
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
81
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}) });
82
Setting a path for the views directory when working with dynamic content in express?
``` const viewsDirectoryPath = path.join(__dirname,"../templates"); app.set('views',viewsDirectoryPath); ```
83
How to structure templates directory?
root => templates => views, partials server.set('views', path)
84
When working with the hbs how can we register the partials directory?
hbs.registerPartials(partialsDirectoryPath);
85
What file extension does handlebar files use?
hbs
86
How to add a partial to a handlebars file?
{{>filename}}
87
Which character is used when setting up 404 pages in node express?
The wild card *
88
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.
89
What are the steps in setting up a basic servier using express?
1. import modules 2. create server 3. set public directory 4. create template machine 5. set views directory 6. register and set partials directory 7. Set up route handlers 8. Set up 404 route handler 9. Start server
90
How to access queries in the route handlers in express?
req.query
91
How to handle query errors in express?
if(!req.query.searchterm){ return res.send({ error:"You must provide a search term" })
92
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) } }) }) ```
93
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') }); ```
94
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')
95
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.
96
Which folder don't you want git to track?
node_modules
97
How to recreate the node_modules folder?
npm install
98
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
99
How to run a script from the package.json file?
npm run scriptname
100
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.
101
How to uninstall a global module?
npm uninstall -g moduleName
102
What does --save-dev do?
npm i module --save-dev installs a package as a dev dependency
103
how are dev dependencies different from regular dependencies?
dev dependencies are not intalled in a production environment, only in a development environment
104
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
105
REST API: What does REST stand for?
Representational State Transfer
106
REST API: CRUD methods
Create: POST Read: GET Update: PATCH Delete: DELETE
107
REST API: Structure of http request
1. Request line: Method, Path, protocol 2. 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 3. Request body that contains Data provded as JSON
108
REST API: Structure of http response
1. Status line: Protocol, status code, text representation of status code 2. Response Headers: Date, server, content type 3. Body: contains JSON data
109
A list of commonly installed npm packages
``` nodemon express request mongodb mongoose validator hbs bcryptjs jsonwebtoken multer sharp @sendgrid/mail env-cmd jest supertest ```
110
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
111
Status codes
100: informational 200: success 300: redirection 400: Client Error codes 500: Server error codes
112
Status codes
httpstatuses.com 100: informational 200: success 300: redirection 400: Client Error codes 500: Server error codes
113
REST API: How to connect or access mongodb database from the server?
1. import the mongoose client require('./db/mongoose.js') ``` 2. import the models const User = require('./db/models/user.js') ``` 3. instantiate an instance of the model in to be used by the routes
114
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) }) });
115
REST API: What is the default status code returned from express?
200
116
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) }) }); ```
117
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.
118
Which algorithm is used for encrypting user passwords?
Bcrypt
119
How to hash a password with bcrypt?
``` const password = 'Red12345!' const hashedPassword = await bcrypt.hash(password,8); ```
120
Can a hashed password be decrypted?
No, it is one way
121
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)
122
What is mongoose middleware?
Allows for the customization of mongoose models
123
Which two mongoose methods can overide middleware?
.findById | .update
124
Which npm package can be used to generate tokens?
jasonwebtoken
125
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.
126
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
127
How to create a web token?
const token = jwt.sign({_id:'abc123'}, 'secretKey');
128
How to verify a toke?
const data = jwt.verify(token,'secretKey'); returns a payload object if verified, otherwise it throws an error
129
Mongoose: How to define methods to be called on the model?
userSchema.statics.methodName(){ | }
130
Mongoose: How to define methods to be called on a model instance?
userSchema.methods.methodName(){}
131
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.
132
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() } }); ```
133
How is authentication tokens sent to the route handlers or server
placed in the header Key: Authorization Value: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTk5NjI0M2FiZTA3ZTBkNDAzYjE5YzUiLCJpYXQiOjE1ODcxNzk5OTN9.eGfK8IoVIbbpyH2SxTR9_Liw7YTGDisVbc5MDMdaqFE
134
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();
135
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}
136
Which npm library allows you to upload media files to the data base?
multer
137
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() });
138
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) } });
139
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}) });
140
How to set an image in html with binary code instead of a file?
141
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')
142
Which module helps to reformat an image?
sharp
143
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; ```
144
How to setup environment variables?
1. install npm i env-cmd 2. Create a dev.env file 3. Setup variables in the file 4. access variables in relevant locations using process.env.ENV_NAME 5. Set the dev script to "env-cmd -f ./dev.env nodemone src/index.js"