Frequently asked - Node JS Interview Questions and Answers - Part 01
1. What is Node.js? What is it used for
Node.js is a run-time JavaScript environment built on top of Chrome’s V8 engine. It uses an event-driven, non-blocking I/O model. It is lightweight and so efficient. Node.js has a package ecosystem called npm.
Node.js can be used to build different types of applications such as web application, real-time chat application, REST API server etc. However, it is mainly used to build network programs like web servers, similar to PHP, Java, or ASP.NET. Node.js was developed by Ryan Dahl in 2009.
2. What is Event-driven programming
Event-driven programming is building our application based on and respond to events. When an event occurs, like click or keypress, we are running a callback function which is registered to the element for that event.
Event driven programming follows mainly a publish-subscribe pattern.
function addToCart(productId){
event.send("cart.add", {id: productId});
}
event.on("cart.add", function(event){
show("Adding product " + event.id);
});
3. What is Event loop in Node.js work? And How does it work
The Event loop handles all async callbacks. Node.js (or JavaScript) is a single-threaded, event-driven language. This means that we can attach listeners to events, and when a said event fires, the listener executes the callback we provided.
Whenever we are call setTimeout
, http.get
and fs.readFile
, Node.js runs this operations and further conitnue to run other code without waiting for the output. When the operation is finished, it receives the output and runs our callback function.
So all the callback functions are queued in an loop, and will run one-by-one when the response has been received.
4. What is REPL in Node.js
REPL means Read-Eval-Print-Loop. It is a virtual environment that comes with Node.js. We can quickly test our JavaScript code in the Node.js REPL environment.
To launch the REPL in Node.js, just opne the command prompt and type node
. It will change the prompt to >
in Windows and MAC.
Now we can type and run our JavaScript easily. For example, if we type 10 + 20
, it will print 30
in the next line.
5. What is the purpose of module.exports
in Node.js
A module encapsulates related code into a single unit of code. This can be interpreted as moving all related functions into a file. Imagine that we created a file called greetings.js
and it contains the following two functions:
module.exports = {
sayHelloInEnglish: function() {
return "HELLO";
},
sayHelloInSpanish: function() {
return "Hola";
}
};
In the above code, module.exports
exposes two functions to the outer world. We can import them in another file as follow:
var greetings = require("./greetings.js");
greetings.sayHelloInEnglish(); // Hello
greetings.sayHelloInSpanish(); //Hola
6. What is require
in Node.js? How will you load external files and libraries in Node.js
require
function is used to load external files and modules that exist in separate files. The basic functionality of require
is that it reads the a JavaScript files, execute the file and then return the export
s object. For example, consider the below code exist in example.js
:
exports.sayHello = function(name) {
console.log("Hello " + name + "!");
}
In another file, we can load this function with require
.
var example = require("./example");
example("World"); //Hello World!
Modules are cached after the first time they are loaded. This means that every call to require(‘example’) will get exactly the same object returned, if it would resolve to the same file.
7. What is the difference between Asynchronous and Non-blocking
Asynchronous literally means not synchronous. We are making HTTP requests which are asynchronous, means we are not waiting for the server response. We continue with other block and respond to the server response when we received.
The term Non-Blocking is widely used with IO. 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 calling thread to sleep.
8. What is Tracing in Node.js
Tracing provides a mechanism to collect tracing information generated by V8, Node core and userspace code in a log file. Tracing can be enabled by passing the --trace-events-enabled
flag when starting a Node.js application.
node --trace-events-enabled --trace-event-categories v8,node server.js
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.
Running Node.js with tracing enabled will produce log files that can be opened in the chrome://tracing
tab of Chrome.”
9. How will you debug an application in Node.js
Node.js includes a debugging utility called debugger
. To enable it start the Node.js with the debug
argument followed by the path to the script to debug.
Inserting the statement debugger;
into the source code of a script will enable a breakpoint at that position in the code:
x = 5;
setTimeout(() => {
debugger;
console.log('world');
}, 1000);
10. Difference between setImmediate()
vs setTimeout()
setImmediate()
and setTimeout()
are similar, but behave in different ways depending on when they are called.
setImmediate()
is designed to execute a script once the current poll (event loop) phase completes.setTimeout()
schedules a script to be run after a minimum threshold in ms has elapsed.
The order in which the timers are executed will vary depending on the context in which they are called. If both are called from within the main module, then timing will be bound by the performance of the process.
11. What is process.nextTick()
setImmediate()
and setTimeout()
are based on the event loop. But process.nextTick()
technically not part of the event loop. Instead, the nextTickQueue
will be processed after the current operation completes, regardless of the current phase of the event loop.
Thus, any time you call process.nextTick()
in a given phase, all callbacks passed to process.nextTick()
will be resolved before the event loop continues.
12. What is package.json
? What is it used for
This file holds various metadata information about the project. This file is used to give information to npm
that allows it to identify the project as well as handle the project’s dependencies.
Some of the fields are: name
, name
, description
, author
and dependencies
.
When someone installs our project through npm
, all the dependencies listed will be installed as well. Additionally, if someone runs npm install
in the root directory of our project, it will install all the dependencies to ./node_modules
directory.
13. What is libuv
libuv
is a multi-platform support library with a focus on asynchronous I/O. It was primarily developed for use by Node.js, but it’s also used by Luvit, Julia, pyuv, and others.
When the node.js project began in 2009 as a JavaScript environment decoupled from the browser, it is using Google’s V8 and Marc Lehmann’s libev
, node.js combined a model of I/O – evented – with a language that was well suited to the style of programming; due to the way it had been shaped by browsers. As node.js grew in popularity, it was important to make it work on Windows, but libev ran only on Unix. libuv
was an abstraction around libev or IOCP depending on the platform, providing users an API based on libev. In the node-v0.9.0 version of libuv libev was removed.
Some of the features of libuv
are:
- Full-featured event loop backed by epoll, kqueue, IOCP, event ports.
- Asynchronous TCP and UDP sockets
- Asynchronous file and file system operations
- Child processes
- File system events
14. What are some of the most popular modules of Node.js
There are many most popular, most starred or most downloaded modules in Node.js. Some of them are:
- express
- async
- browserify
- socket.io
- bower
- gulp
- grunt
15. What is express.js
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Express is a light-weight web application framework to help organize our web application into a MVC architecture on the server side. We can use a variety of choices for your templating language like EJS, Jade.
Express.js basically helps you manage everything, from routes, to handling requests, response and views. An example of an Express.js routing is as follow:
var express = require('express')
var app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
res.send('hello world')
})
16. What is middlewares? What is the concept of middlewares in Express.js
Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
Bind application-level middleware to an instance of the app object by using the app.use()
and app.METHOD()
functions, where METHOD
is the HTTP method of the request that the middleware function handles (such as GET
, PUT
, or POST
) in lowercase.
var app = express()
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
17. What is EventEmitter
in Node.js
All objects that emit events are instances of the EventEmitter
class. These objects expose an eventEmitter.on()
function that allows one or more functions to be attached to named events emitted by the object.
When the EventEmitter
object emits an event, all of the functions attached to that specific event are called synchronously.
var events = require('events');
var eventEmitter = new events.EventEmitter();
var myEvent = function ringBell() {
console.log('Event is emitted');
}
eventEmitter.on('emitEvent', ringBell);
eventEmitter.emit('emitEvent');
18. What is Streams
in Node.js
Streams are pipes that let you easily read data from a source and pipe it to a destination. Simply put, a stream is nothing but an EventEmitter
and implements some specials methods. Depending on the methods implemented, a stream becomes Readable, Writable, or Duplex (both readable and writable).
For example, if we want to read data from a file, the best way to do it from a stream is to listen to data event and attach a callback. When a chunk of data is available, the readable stream emits a data event and your callback executes. Take a look at the following snippet:
var fs = require('fs');
var readableStream = fs.createReadStream('textFile.txt');
var fileData = '';
readableStream.on('data', function(chunk) {
data += chunk;
});
readableStream.on('end', function() {
console.log(data);
});
Types of streams are: Readable, Writable, Duplex and Transform.
19. What is Child Process
and Cluster
? What are the difference
Child Process
in Node.js is used to run a child process under Node.js. There are two methods to do that: exec
and spawn
. The example for exec
is:
var exec = require('child_process').exec;
exec('node -v', function(error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
We are passing our command as our first argument of the exec
and expect three response in the callback. stdout is the output we could expect from the execution.
Cluster
is used to split a single process into multiple processes or workers, in Node.js terminology. This can be achieved through a cluster module. The cluster module allows you to create child processes (workers), which share all the server ports with the main Node process (master).
A cluster is a pool of similar workers running under a parent Node process. Workers are spawned using the fork()
method of the child_processes
module. Cluster is multiple processes to scale on multi cores.
20. How can we avoid Callback Hell in Node.js
Callback hell refers to heavily nested callbacks that have become unreadable and hard to debug. We can use async
module.
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Consider we have two functions which runs sequentially:
async.waterfall([firstFunction, secondFunction], function() {
console.log('done')
});