Node Flashcards
What is Node.js? Where can you use it?
Node.js is a single-threaded, open-source, cross-platform runtime environment used to build server-side and networking applications. It uses event-driven, non-blocking I/O architecture, which makes it efficient and suitable for real-time applications.
Why use Node.js?
Explanation: It uses fewer resources and memory because it is single threaded, it has wide adoption with many open source pacakages available, it is multi-platform and it simplifies the full stack as you can use just one language: Javascript.
Use: It’s best used for real time applications that aren’t data intensive. For programs that require more data processing a multi-threaded language like Java is a better choice.
What are the features of Node.js?
Explanation: Node innately offers valuable resources that standalone JavaScript environment doesn’t allow, such as access to http and fs modules.
Use: Through node we have access to the V8 Engine via JavaScript, where we have browser functionalities in our JavaScript environment. We can access packages via npm to install established libraries, or require pre-established modules for things like server creation and file storage.
Example: const http = require(‘http’) Allows us to access Node.js web server module (ES6) so we can use http methods such as createServer.
const fs = require(‘fs’); Allows us actions such as reading and writing to files in a file system
How do you update NPM to a new version in Node.js?
Explanation: With Mac or Linux systems it is rather easy just type the command npm install -g npm@latest into the terminal to update npm. With Windows it’s a little more complex as you will need to either modify the Window’s installation PATH or remove the npm files from the nodejs install directory then update npm in the terminal.
Windows solution, just go to the Node.js site, click the download button on the homepage and execute the installer program.
Thankfully it took care of everything and with a few clicks of ‘Next’ button I got the latest 0.8.15 Node.js version running on my Windows 7 machine.
Why is Node.js Single-threaded?
Explanation: Node.js is single-threaded for async processing. By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved instead of the typical thread-based implementation.
It turns out to be more performant and scalable than other multithreaded alternatives such as Java.
The beauty of the event loop is not of running everything in a single thread, but it’s available to “put aside” long time-consuming I/O operations to keep the execution of other instructions. This is the reason why we get fast responses even though we could have multiple users making requests to a Node.js API at the same time.
Explain callback in Node.js.
Explanation: A callback function is called after a given task. All APIs of Node are written to support callbacks.
Use: Callbacks allow other code to be run in the meantime and prevents any blocking. Being an asynchronous platform, Node.js heavily relies on callback.
What is callback hell in Node.js?
Explanation: This is a big issue caused by coding with complex nested callbacks. Imagine each and every callback takes an argument that is a result of the previous callbacks. In this manner, The code structure looks like a pyramid, making it difficult to read and maintain. Also, if there is an error in one function, then all other functions get affected.
Use: This should be avoided.
Example:
fs.readdir(source, function (err, files) {
if (err) {
console.log(‘Error finding files: ‘ + err)
} else {
files.forEach(function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function (err, values) {
if (err) {
console.log(‘Error identifying file size: ‘ + err)
} else {
console.log(filename + ‘ : ‘ + values)
aspect = (values.width / values.height)
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect)
console.log(‘resizing ‘ + filename + ‘to ‘ + height + ‘x’ + height)
this.resize(width, height).write(dest + ‘w’ + width + ‘_’ + filename, function(err) {
if (err) console.log(‘Error writing file: ‘ + err)
})
}.bind(this))
}
})
})
}
}) //note this long line of stacking brackets is often a tell of callback hell
How do you prevent/fix callback hell?
Explanation: One of the most common ways is to use promises (an object that represents the eventual completion or failure of an async operation and its value). Once each step is finished and we have our value, we can run then() method to call the async callback or if it fails we can catch an error. We could also just keep our code shallow and modularize (make each block of code do one thing only).
Example:
houseOne()
.then(data=>console.log(data)
.then(houseTwo)
.then(data=>console.log(data)
.then(houseTwo)
Explain the role of REPL in Node.js.
Explanation: The Node.js Read-Eval-Print-Loop (REPL) is an interactive shell that processes Node.js expressions. The shell reads JavaScript code the user enters, evaluates the result of interpreting the line of code, prints the result to the user, and loops until the user signals to quit.
Use: The REPL is bundled with with every Node.js installation and allows you to quickly test and explore JavaScript code within the Node environment without having to store it in a file. Entering “node” in the terminal starts the REPL
Example:
sammy@b6755984:~$ node //press enter on “node” to get “>”, indicating the start
Welcome to Node.js v14.19.0.
Type “.help” for more information.
> 2+2 //used REPL to evaluate simple math
4
Name the types of API functions in Node.js.
Explanation: There are two types; Asynchronous, Non-blocking functions and Synchronous, Blocking functions
Example: Asynchronous examples would be emails and online forums. Synchronous examples would be instant messaging and video calls.
What are the functionalities of NPM in Node.js?
Explanation: NPM serves two main purposes; being an online repository of open-source Node.js projects and a command line utility for interacting with said repository.
Use: Typically it is used to install packages, manage versions and manage project dependencies.
What is the difference between Node.js and Ajax?
What are “streams” in Node.js? Explain the different types of streams present in Node.js.
Explanation: Streams are objects that enable you to read data or write data continuously.
Use: There are four types of streams:
Readable – Used for reading operations
Writable − Used for write operations
Duplex − Can be used for both reading and write operations
Transform − A type of duplex stream where the output is computed based on input
Node.js and Ajax (Asynchronous JavaScript and XML) are the advanced implementations of JavaScript. They all serve entirely different purposes.
Ajax is primarily designed for dynamically updating a particular section of a page’s content, without having to update the entire page.
Node.js is used for developing client-server applications.
Explain chaining in Node.js.
Chaining in Node.js can be achieved using the async npm module. In order to install the async module, we need to run the following script in our directory:
npm init
npm i async
There are two most commonly used methods for chaining functions provided by the async module:
parallel(tasks, callback): The tasks is a collection of functions that runs parallel in practice through I/O switching. If any function in the collection tasks returns an error, the callback function is fired. Once all the functions are completed, the data is passed to the callback function as an array. The callback function is optional.
series(tasks, callback): Each function in tasks run only after the previous function is completed. If any of the functions throw an error, the subsequent functions are not executed and the callback is fired with an error value. On completion of tasks, the data is passed into the callback function as an array.
Chaining is a mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations.
What are Globals in Node.js?
Explanation: Node.js Global Objects are the objects that are available in all modules. Global Objects are built-in objects that are part of the JavaScript and can be used directly in the application without importing any particular module.
Use: Common built-in modules, functions, strings and objects used widely in Node.
Example: setTimeout() is a global function used to run a callback after at least x milliseconds:
function printHello() {
console.log(‘Hello World!’);
}
//call printHello() after 2 seconds
setTimeout(printHello, 2000);