NodeJS Flashcards
What is the difference between NPM and NVM?
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
What is the difference between a node module and a node package?
Module
Encapsulates all related code into a single file
Package
One or more modules
What is Node.js and where can you use it?
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
What are the pros and cons of Node.js?
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 does Node.js work?
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
Why is Node.js single-threaded?
More performance and scalability can be achieved by doing async processing on a single thread instead of typical thread-based implementation
How does Node.js handle concurrency?
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
What is the Event Loop in Node.js?
Listens for async events which gets actioned by event handlers
Foundation of non-blocking I/O
EventEmitter => events => Event Loop => event handlers
What is a callback?
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
What are the advantages of using promises instead of callbacks?
- The flow of async logic is more specified and structured
- Low coupling
- Built-in error handling
- Improved readability
What is an EventEmitter?
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
What is Express.js?
Node.js web application framework
What is the difference between process.nextTick() vs process.setImmediate()?
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
What is the REPL?
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
What is piping?
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
What is callback hell?
Result of intensively nested, unreadable and unmanageable callbacks
Improper implementation of async logic causes callback hell
What is middleware?
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
What does I/O mean?
Input/Output
Accesses anything outside your application - loaded into the machine memory to run the program once the machine has started
What is the difference between Node.js, AJAX and JQuery?
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
What are the two types of API functions in Node.js?
- Asynchronous, non-blocking functions
- Synchronous, blocking functions
What does the runtime environment mean in Node.js?
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
What are the types of tasks that should be done asynchronously?
- Heavy computation
- Anything requiring blocking operations
Why is libuv needed in Node.js and what are its features?
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
What is the difference between fork() vs spawn() method in Node.js?
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
What is the difference between asynchronous vs non-blocking?
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
What is the difference between process.nextTick() vs setImmediate()?
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
Explain the usage of NODE_ENV?
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
Which data type is only available in Node.js and not available in browser’s JavaScript?
Buffer
What is the difference between a buffer vs stream?
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
What are some of the events fired by streams?
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
What is the purpose of module.exports?
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
What is the purpose of a package.json file?
Contains the metadata relevant to the project including project dependencies
What are the types of memory leaks in Node.js
- Global resources
- Closures
- Caching
- Promises
How do you resolve the “Process out of memory exception”?
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=
What is control flow and how does it work?
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
What is chaining?
A mechanism to connect the output of one stream to another stream creating a chain of stream operations
Normally used with piping operations
What are some timing features of Node.js?
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
What is the reactor pattern in Node.js?
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
What are migrations and why are they used ?
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
What is knex.js?
SQL builder with built-in migration framework
Keeps track of executed migration scripts and rolls back unsuccessful migrations if needed
Why should you separate app and server in Express?
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
What is an error-first callback?
Pattern used across async methods in Node.js
How does Node.js handle child threads?
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
What is the preferred way of resolving unhandled exceptions and why using a try/catch wouldn’t work?
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
What is LTS and why is it important?
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
How can you make sure your dependencies are safe?
Automate the security audit of your dependencies
Security audit options:
- Snyk
- npm outdated
- npm audit
What are some popular Node.js packages and their uses?
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
How does assert() work in Node.js?
Provides a way of testing expressions
If expression evaluates to 0 of false, then the program is terminated