Node Flashcards

1
Q

What is Node.js? Where can you use it?

A

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.

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

Why use Node.js?

A

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.

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

What are the features of Node.js?

A

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

How do you update NPM to a new version in Node.js?

A

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.

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

Why is Node.js Single-threaded?

A

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.

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

Explain callback in Node.js.

A

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.

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

What is callback hell in Node.js?

A

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

How do you prevent/fix callback hell?

A

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)

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

Explain the role of REPL in Node.js.

A

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

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

Name the types of API functions in Node.js.

A

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.

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

What are the functionalities of NPM in Node.js?

A

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.

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

What is the difference between Node.js and Ajax?

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

What are “streams” in Node.js? Explain the different types of streams present in Node.js.

A

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.

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

Explain chaining in Node.js.

A

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.

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

What are Globals in Node.js?

A

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);

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

What is Event-driven programming?

A

Event-driven programming is a paradigm that involves building applications that send and receive events. When the program emits events, the program responds by running any callback functions that are registered to that event and context, passing in associated data to the function. With this pattern, events can be emitted into the wild without throwing errors even if no functions are subscribed to it.

A common example of this is the pattern of elements listening to DOM events such as click and mouseenter, where a callback function is run when the event occurs.

document.addEventListener(“click”, function(event) {
// This callback function is run when the user
// clicks on the document.
})
Without the context of the DOM, the pattern may look like this:

const hub = createEventHub()
hub.on(“message”, function(data) {
console.log(${data.username} said ${data.text})
})
hub.emit(“message”, {
username: “John”,
text: “Hello?”
})

An event-driven programming approach uses events to trigger various functions. An event can be anything, such as typing a key or clicking a mouse button.

A call-back function already registered with the element executes whenever an event is triggered.

17
Q

What is Event loop in Node.js? And How does it work?

A

Explanation: The Event loop handles all async callbacks. We can attach listeners to events, and when a said event fires, the listener executes the callback we provided.
Use: Whenever we call setTimeout, http.get and fs.readFile, Node.js runs the operation and continues to run other code without waiting for the output. When the operation is finished, it receives the output and runs our callback function. All the callback functions are queued in an loop, and will run one-by-one when the response has been received.

18
Q

What is the purpose of module.exports in Node.js?

A

Explanation: In Node.js, a module encapsulates all related code into a single unit of code by moving all relevant functions into a single file.
Use: You may export a module with the module.exports function, which lets it be imported into another file using require

19
Q

What is the difference between Asynchronous and Non-blocking?

A

Explanation: Asynchronous literally means not synchronous. HTTP requests which are asynchronous, means we are not waiting for the server response. The program continues with other code blocks and deals with the server response when it is received. The term Non-Blocking is widely used with I/O. For example non-blocking read/write calls return with whatever they can do and expect caller to execute the call again. Read will wait until it has some data and put the calling thread to sleep.

20
Q

What is Tracing in Node.js?

A

Explanation: Tracing provides a mechanism to collect tracing information generated by V8, Node core and userspace code in a log file.
Use: Tracing can be enabled by passing the –trace-events-enabled flag when starting a Node.js application. The set of categories for which traces are recorded can be specified using the –trace-event-categories flag followed by a list of comma separated category names. By default the node and v8 categories are enabled. Log files can be opened in the chrome://tracing tab of Chrome.

21
Q

How will you debug an application in Node.js?

A

Explanation: Typically using the debugger utility and console.log(). I would place debugger statements in the code wherever I would like a breakpoint inserted and then run the script with node and debug enabled.

22
Q

Difference between setImmediate() and setTimeout()?

A

Explanation: setImmediate() is to schedule the immediate execution of callback after I/O (input/output) event callbacks and before setTimeout and setInterval. setTimeout() is to schedule execution of a one-time callback after delay milliseconds. both are async.
Use: Inside an I/O cycle, the setImmediate() should execute before setTimeout({},0).
Example:
const fs = require(‘fs’);

fs.readFile(__filename, () => {
setTimeout(() => {
console.log(‘timeout’);
}, 0);
setImmediate(() => {
console.log(‘immediate’);
});
});

23
Q

What is process.nextTick()?

A

Explanation: Every time the event loop takes a full trip, we call it a tick. When we pass a function to process.nextTick(), we instruct the engine to invoke this function at the end of the current operation, before the next event loop tick starts. process.nextTick() is actually faster
Use: Calling setTimeout(() => {}, 0) will execute the function at the end of next tick, much later than when using nextTick() which prioritizes the call and executes it just before the beginning of the next tick.
Example:
process.nextTick(() => {
// do something
});

24
Q

What is package.json? What is it used for?

A

Explanation: All npm packages contain a file, usually in the project root, called package.json - this file holds various metadata relevant to the project. It’s a central repository of configuration for tools, for example. It’s also where npm and yarn store the names and versions for all the installed packages.
Use: This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies. It can also contain other metadata such as a project description, the version of the project in a particular distribution, license information, even configuration data - all of which can be vital to both npm and to the end users of the package. The package.json file is normally located at the root directory of a Node.js project.

25
Q

What is libuv?

A

Explanation: Node.js has two major dependencies, written in C. One is the V8 engine, which converts JavaScript into machine code, and the other is libuv, which provides access to the event loop and the thread pool.
Use: Similar to how client-side JavaScript utilizes Web APIs to take advantage of asynchronous processes, libuv allows Node.js to perform non-blocking input-output (I/0) operations with the event loop. More expensive tasks are offloaded to the thread pool.
Example: setTimeout() works the same in the libuv event loop as it would in a browser environment, executing a callback function after a minimum time is specified. The thread pool handles more intensive tasks, such as DNS lookup and encryption.

26
Q

What are some of the most popular modules of Node.js?

A

Express, AsyncJS, Axios, Morgan

27
Q

What is EventEmitter in Node.js?

A

Explanation: EventEmitter is a class that holds all the objects that can emit events.
Use: Whenever an object from the EventEmitter class throws an event, all attached functions are called upon synchronously.