NodeJS Flashcards

1
Q

What is the difference between NPM and NVM?

A

Node Package Manager

  • Shipped with NodeJS
  • CLI to manage remote node modules
  • Allows you to publish, download and update modules
  • Stores remote modules in node_modules folder

Node Version Manager (NVM)
- Allows you to switch between multiple versions of Node - Recommended way to install Node

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

What is the difference between a node module and a node package?

A

Module
Encapsulates all related code into a single file

Package
One or more modules

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

What is Node.js and where can you use it?

A

JavaScript runtime environment and library

Uses to create server-side applications

Use cases:

  • Data-intensive apps - uses the asynchronous, event-driven model
  • I/O intensive web apps (video streaming)
  • Realtime web apps
  • Microservices
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the pros and cons of Node.js?

A

Pros

  • Low latency and high throuput due to its non-blocking approach
  • Everything is asynchronous
  • Great concurrency

Cons

  • Not suitable for heavy computational tasks
  • Not suitable for CPU-intensive tasks since it is single-threaded
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does Node.js work?

A

Runs on a single process with requests being processed on a single thread

When a request is sent, Node.js places it in an event queue and uses the Event Loop to listen for async events

If a request is non-blocking, the request is immediately sent back to the client

If a request is blocking, request is sent to the worker thread pool and when it’s finished, it will be sent back to the Event Loop to be sent back to the client

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

Why is Node.js single-threaded?

A

More performance and scalability can be achieved by doing async processing on a single thread instead of typical thread-based implementation

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

How does Node.js handle concurrency?

A

Node.js adheres to the Single Threaded Event Loop Model

Aysnc calls are handled by the libuv library which sets up a thread pool to handle concurrent requests

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

What is the Event Loop in Node.js?

A

Listens for async events which gets actioned by event handlers

Foundation of non-blocking I/O

EventEmitter => events => Event Loop => event handlers

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

What is a callback?

A

A function that’s passed into another function as a parameter and only runs after its parent function has finished executing

Uses nested functions to ensure async tasks are handled in the desired order - can easily lead to callback hell

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

What are the advantages of using promises instead of callbacks?

A
  • The flow of async logic is more specified and structured
  • Low coupling
  • Built-in error handling
  • Improved readability
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is an EventEmitter?

A

Module that facilitates communication between objects in Node.js

Consists of 2 main features:

  • Emitting name events
  • Registering/unregistering listener functions

Whenever an object from the EventEmitter class throws an event, all registered listeners are called synchronously - ensures proper sequencing of events and avoids race conditions

As best practice, listeners should always be added for “error” events

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

What is Express.js?

A

Node.js web application framework

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

What is the difference between process.nextTick() vs process.setImmediate()?

A

process. nextTick()
- Postpones execution of action until the next pass around the event loop and calls the cb function once event loop’s current execution is complete

process. setImmediate()
- Executes a callback on the next cycle of the event loop and returns control to the event loop for any I/O operations

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

What is the REPL?

A

Read Eval Print Loop

Represents a computer environment

Read - read user’s input; parse and store in memory

Eval - evaluates data structure

Print - print result

Loop - loops through commands until user terminates it

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

What is piping?

A

A mechanism to connect the output of one stream to another stream

Used to retrieve data from one stream and pass output to another stream

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

What is callback hell?

A

Result of intensively nested, unreadable and unmanageable callbacks

Improper implementation of async logic causes callback hell

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

What is middleware?

A

Functions that sit between the route request and route response

Once the function has finished executing, it can either finish the request-response cycle or invoke the next middleware in the stack

ie. authentication, transforming request, logging

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

What does I/O mean?

A

Input/Output

Accesses anything outside your application - loaded into the machine memory to run the program once the machine has started

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

What is the difference between Node.js, AJAX and JQuery?

A

Node.js
JavaScript runtime to write backend applications

AJAX
Technology used to send requests to web servers and retrieve data from them without reloading the page

JQuery
JavaScript library that helps with frontend development

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

What are the two types of API functions in Node.js?

A
  • Asynchronous, non-blocking functions

- Synchronous, blocking functions

21
Q

What does the runtime environment mean in Node.js?

A

The environment your application is running in - Node.js runs on V8 JavaScript engine

ie. how much RAM, what version of node, what OS etc

22
Q

What are the types of tasks that should be done asynchronously?

A
  • Heavy computation

- Anything requiring blocking operations

23
Q

Why is libuv needed in Node.js and what are its features?

A

Libuv is a library written in C that Node.js uses to abstract non-blocking operations

Features:

  • Event-driven async I/O integration
  • Allows CPU and other resources to be used while still performing I/O operations efficiently
24
Q

What is the difference between fork() vs spawn() method in Node.js?

A

fork()
Particular case of spawn() which generates a new V8 instance

Multiple workers can run on a single node for multiple tasks

spawn()
Launches a new process with a set of commands

Does not generate a new V8 instance

Used when a child process returns a large amount of data to the node

25
Q

What is the difference between asynchronous vs non-blocking?

A

Asynchronous
For a message sent, we will not receive a response immediately

An acknowledgement is received when the action is performed - improves performance and efficiency

Non-blocking
Does not stop/block any operations - receives a response immediately with whatever data is available

If no data available, it returns an error

Mostly used with I/O operations

26
Q

What is the difference between process.nextTick() vs setImmediate()?

A

process.nextTick()
Postpones execution until next iteration of the Event Loop and calls the callback once Event Loop’s current execution is complete

setImmediate()
Executes a callback on the next iteration of the Event Loop and returns control to the Event Loop for any I/O operations

27
Q

Explain the usage of NODE_ENV?

A

Environment variable made popular by the express framework

When the node application is run, it can check the value of the environment variable and do different things based on it

ie. use caching for production, not for development

28
Q

Which data type is only available in Node.js and not available in browser’s JavaScript?

A

Buffer

29
Q

What is the difference between a buffer vs stream?

A

Buffer
Storage of raw data

Stream
Objects that enable you to read/write data continuously

Types:

  • Readable - reading operations
  • Writable - writing operations
  • Duplex - read/write operations
  • Transform - type of duplex stream where output is computed based on input
30
Q

What are some of the events fired by streams?

A

Each type of stream is an EventEmitter instance which fires different events at different times

Events:

  • Data - fired when data is available to read
  • End - fired when no more data to read
  • Error - fired when it encounters an error
  • Finish - fired when all data has been flushes
31
Q

What is the purpose of module.exports?

A

Give instructions to Node.js about which part of the code should be exported from a given file to be shared with other files

Encapsulates similar functions in a file and improves project structure

32
Q

What is the purpose of a package.json file?

A

Contains the metadata relevant to the project including project dependencies

33
Q

What are the types of memory leaks in Node.js

A
  • Global resources
  • Closures
  • Caching
  • Promises
34
Q

How do you resolve the “Process out of memory exception”?

A

Occurs when your app runs out of memory - when default memory allocated to the program has exceeded during execution

Resolved by increasing the default memory allocated by using a node CLI command

node –max-old-space-size=

35
Q

What is control flow and how does it work?

A

Order in which instructions in your program are executed

Code is executed sequentially unless it runs across structures that change the control flow ie. loops/conditionals

Since I/O operations in Node.js are non-blocking, control flow cannot be linear - registers a callback to the Event Loop and passes control back to the node so it can continue with the flow

36
Q

What is chaining?

A

A mechanism to connect the output of one stream to another stream creating a chain of stream operations

Normally used with piping operations

37
Q

What are some timing features of Node.js?

A

setTimeout()
Implement delays in code execution

setInterval()
Executes code blocks multiple times

process.nextTick()
Postpones execution until next iteration of the Event Loop and calls the callback once Event Loop’s current execution is complete

setImmediate()
Executes a callback on the next iteration of the Event Loop and returns control to the Event Loop for any I/O operations

38
Q

What is the reactor pattern in Node.js?

A

Pattern for non-blocking I/O operations commonly used in event-driven architecture

Consist of 2 components:

  • Reactor - dispatches I/O event to appropriate handlers
  • Handler - handles the event
39
Q

What are migrations and why are they used ?

A

Controlled set of changes to modify data in a db and prevent data loss

Help transition the db from current state to a new, desired state

40
Q

What is knex.js?

A

SQL builder with built-in migration framework

Keeps track of executed migration scripts and rolls back unsuccessful migrations if needed

41
Q

Why should you separate app and server in Express?

A

Ensures server logic is encapsulated and decoupling from application logic

Allows for reusability and increases scalability

app. js file
- Contains business logic and its execution
- Contains access to db and models
- Consist of 2 main components - routes and controllers

server. js file
- Setting up server, port and routes
- Initialisation of middleware

42
Q

What is an error-first callback?

A

Pattern used across async methods in Node.js

43
Q

How does Node.js handle child threads?

A

Node.js is a single-threaded language and uses multiple threads in the background to execute async code which is not exposed to the developer

Node.js provides 2 methods to execute code in parallel to the Event Loop:

  • child_process module: gives node the ability to run child processes by accessing OS commands
  • worker_threads module: useful for performing CPU-intensive operations
44
Q

What is the preferred way of resolving unhandled exceptions and why using a try/catch wouldn’t work?

A

Two ways to resolve unhandled exceptions:

  • Using a try/catch block
  • Using the process object

Using a try/catch block will not work for asynchronously thrown errors (ie. errors thrown in a setTimeout()) but can be caught using process.on(“uncaughtException”, callback) as it is always listening to events

45
Q

What is LTS and why is it important?

A

Long Term Support

LTS versions of Node.js are supported for 18 months and is focused on stability and security making it a better choice for production

Current release versions have a shorter lifespan and more frequent updates to the code

46
Q

How can you make sure your dependencies are safe?

A

Automate the security audit of your dependencies

Security audit options:

  • Snyk
  • npm outdated
  • npm audit
47
Q

What are some popular Node.js packages and their uses?

A

Express
Mimimal web framework

Lodash
Utility library

Date-fns
Helps with parsing, formatting dates

Nodemon
Used in development to watch for changed files and automatically restarts the node app

Winston
Logging library

48
Q

How does assert() work in Node.js?

A

Provides a way of testing expressions

If expression evaluates to 0 of false, then the program is terminated