NodeJS Flashcards

1
Q

What is Node JS?

A

As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications.

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

How does Node work?

A

Node is a single threaded which in the background uses multiple threads to execute asynchronous code.
When a request arrives, that single thread is used to handle that request. If that request takes time, the single thread moves to serve another request.

When the 1st request is finished it puts a message in an Event Queue (which node is continuosly monitoring in the background

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

Which are the apps to go with node?

A
  • Because of being able to execute asynchronous code node is ideal for apps that include a lot of disc or network access (I/O-intensive apps).
  • In the contrast, node should not be used in CPU-intensive apps (video-encoding, etc.)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the basic modules that are built in the core of node?

A
os - operating system
fs - file system
events 
http
path
process
query strings
stream
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the scope of variables in nodeJS app?

A

Contrary to the browser environment, where variables are declared in the global (window) object, these variables are not declared in the global. scope in node.

They are scoped only to the file, they are in.

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

How to use variables outside of a module?

A

In order to use a function or variable outside of the node module, we need to explicitly export it (make it public).

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

How do you export and import functions outside of modules?

A
You can export functions and variables, by attaching them to a modules.exports object.
By exporting functions, we make them public, however, they still maintain access to the variables that were defined in the module they are in

modules.exports.log = log;

To load a module, we use require() function.
const {log} = require(‘./logger’);

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

What is a wrapper function when it comes to working with node modules.

A

Node modules wraps its modules inside of an IIFE function.

function(exports, require, module, __filename, __dirname){};

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

What does path module do?

A
The path module provides utilities for working with file and directory paths. It can be accessed using:
const path = require('path')

1) The path.parse() method returns an object whose properties represent significant elements of the path. Trailing directory separators are ignored, see path.sep.

The returned object will have the following properties:

dir 
root 
base 
name 
ext 

2)

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

What are environmental variables?

A

Environmental variables, are generally where we store sensitive information (passwords, logins, usernames, apis). That should never go to your github.

They are located in variables.env

Node package require(‘dotenv’).config({path: ‘variables.env’}) allows us to access whatever is in variables.env and access it by process.env.nameOfVariable.

Environment variables do not need to be imported into files across the app -> They are located on the node process and are accessible from anywhere.

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

What is routing?

A

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

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

What are the differences between asynchronous and synchronous methods for file system module?

A

const fs = require(‘fs’);

All of the methods in the filesystem module come in synchronous and asynchronous version.

We should always use asynchronous version, because we do not want to block the single thread that node uses to requests from the clients.

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

What are middleware functions?

A

Middleware functions are functions that have access to the req, res objects and the next middleware function in the applications cycle.

Middleware functions are functions that are inbetween req and res and can perform some actions (like executing any code, make changes to the res, req objects). If the middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function.

We pass the middlewares functions to the router.METHOD, those middlewares are specific for an endpoint.

However, we may also define global middlewares. In order to do that we use
const express = require('expess')
const app = express();

app.use keyword, in which we pass a callback function.

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

How do we read and write to files using node?

A

const fs = require(‘fs’);

fs. readFileSync(‘./path’, {encoding: ‘utf-8’});
fs. writeFileSync(‘./path’, textOut);

With node, all asynchronous versions of the methods are much more popular.
When it comes to fs.readFile() and fs.writeFile(), we need to provide a callback function as the last argument, which in case of readFile accepts two arguments (err, data1) =>
if (err) return console.log(err);

In case of write, we need to only specify the error.

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

How do you start a webserver in node?

A
In plain node, we need to declare a server variable, by using const server = http.createServer((req,res) => res.end('')) from http module.
Then we need to server.listen(port,'127.0.0.1', callback);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are Event Lop and Thread Pool?

A

NodeJS process operates on a single thread.
When a program is executed it
1. Initializes a program -> 2. Executes top-level code ->3. Requires modules -> 4. Registers event callbacks -> 5. Starts event loop

  • Event loop is all the application code that is inside callback functions is executed.
  • Since, node JS has an event-driven architecture and is built around callback functions, all the events like requests, reading files, timer expiry will emit events, that will be handled by he event loop.

Tasks that are heavy are delegated by the event loop to the thread pool (by default, we are given additional 4 threads) - this all happens behind the scenes

17
Q

What are the guidelines, so you do not block the event loop?

A
  • Don’t use sync versions of functions in fs, crypto and zlib modules in your callback functions
  • Don’t perform complex calculations (e.g. loops inside loops)
  • Be careful with JSON in large objects
  • Don’t use too complex regular expressions (e.g. nested quantifiers)
18
Q

How do you listen to and create events?

A

You can either use built in events or create your custom events if necessary.

Most of the modules in node, will come with events that are fired, whenever some actions are completed. For example
http module
const server = http.createServer()
has built in events that fire on request or close.
server.on(‘request’, callback);

In order to create your own custom events, you need to import a class from events module.
const EventEmitter = require('events');
const myEmitter= new EventEmitter();
// Create a custom event
myEmitter.on('newSale', callback);
// Emit the custom event
myEmitter.emit('newSale')
19
Q

What are streams?

A

Streams are another core NodeJS Concept.
They are used to process (read and write) data piece by piece (chunks), without completing the whole read or write operation and therefore without keeping all the data in memory.

  • Readable streams - Strreams from which we can read (consume) data, http requests, events: data, end, functionts: pipe(), read()
  • Writable streams - streams to wchich we can write data , http responses, fs write streams, events: drain, finish, functions: write(), end()
  • Duplex streams - streams that are both readable andwritable, websocket from net module,
  • Transform streams - dupex stream that transform data as it is written or read, zlib gzip creation.

When dealing with readable streams, pipe method is extremely useful -> it matches the pace of reading by the readable stream to the pace of sending requests. It solves the problem of backpressure.
in order to implement that we need to:

server.on("request", (req, res) => {
    const readable = fs.createReadStream("test-file.txt");
    readable.pipe(res);
});
20
Q

What is the difference between module.exports and exports

A

module. exports is the returned object.
- use module.exports to export one single variable, e.g. one class or one function
- Use exports to export multiple named variables

21
Q

What is JSEND?

A

JSend is a specification that lays down some rules for how JSON responses from web servers should be formatted. JSend focuses on application-level (as opposed to protocol- or transport-level) messaging which makes it ideal for use in REST-style applications and APIs.

the response json object should include

status: ‘success’ | ‘fail’ | ‘error’
data: {} if success
message: ‘’ if error or fail

22
Q

How do you get access to command line arguments that were passed when running node from the command line?

A

process.argv

The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched.

We can then access process.argv[2] in order to invoke some functions based on a switch/ if statement for a script (for example to import data to the db).

23
Q

How do you promisify a function in node?

A
Node has a built in module called util
const util = require('util');

Then we can await the result of
promisify(jwt.verify)(token, process.env.JWT_SECRET)