Frequently asked - Node JS Interview Questions and Answers - Part 02
21. What is the difference between Node.js vs Ajax?
The difference between Node.js and Ajax is that, Ajax (short for Asynchronous JavaScript and XML) is a client side technology, often used for updating the contents of the page without refreshing it. While,Node.js is Server Side JavaScript, used for developing server software. Node.js does not execute in the browser but by the server.
22. What is File System in Node.js
Node.js provides a File system module to read and write data to a file in the memory. This module comes with Node.js by default in the name of fs
. To read a file:
var fs = require("fs");
fs.readFile("foo.txt", "utf8", function(err, data) {
console.log(data);
});
23. What is the difference between readFile
vs createReadStream
in Node.js
readFile - is for asynchronously reads the entire contents of a file. It will read the file completely into memory before making it available to the User. readFileSync
is synchronous version of readFile
.
createReadStream - It will read the file in chunks of the default size 64 kb which is specified before hand.
24. How to support multi-processor platforms in Node.js
Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster
module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port.
25. How to install a node module locally and globally? How to add them into package.json
By default, Node.js installs the module locally in the ./node_modules
directory. To install a module globally and to make them available everywhere, we need to include the -g
flag.
npm install express -g
To save the installed module to the package.json
under dependencies
, add --save
flag with the package name. To add under deveDependencies
add --save-dev
.
26. What are Global objects in Node.js
Node.js has some Global objects which are available in all modules. Some of these objects are not actually in global scope but in the module scope.
__dirname
: The directory name of the current module. This the same as thepath.dirname()
of the__filename
.__filename
: The file name of the current module. This is the resolved absolute path of the current module file.exports
: A reference to themodule.exports
that is shorter to type.exports
is not actually a global but rather local to each module.require
: To require modules.require
is not actually a global but rather local to each module.
27. What is crypto
in Node.js? How do you cipher the secured information in Node.js
The crypto
module in Node.js provides cryptographic functionality that includes a set of wrappers for OpenSSL’s hash, HMAC, cipher, decipher, sign and verify functions.
var crypto = require('crypto');
var secret = 'abcdefg';
var hash = crypto.createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash);
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
28. What is zlib
? How do you compress a file in Node.js
The zlib
module provides compression functionality implemented using Gzip and Deflate/Inflate.
var zlib = require('zlib');
var gzip = zlib.createGzip();
var fs = require('fs');
var inp = fs.createReadStream('input.txt');
var out = fs.createWriteStream('input.txt.gz');
inp.pipe(gzip).pipe(out);
Calling .flush()
on a compression stream will make zlib
return as much output as currently possible. This may come at the cost of degraded compression quality, but can be useful when data needs to be available as soon as possible.
29. What is Buffer
in Node.js
Buffers are instances of the Buffer
class in node, which is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren’t resizable and have a whole bunch of methods specifically for binary data.
Pure JavaScript does not handle straight binary data very well. This is fine on the browser, where most data is in the form of strings. However, Node.js servers have to also deal with TCP streams and reading and writing to the filesystem, both which make it necessary to deal with purely binary streams of data. Below are the ways to create new buffers:
var bufferOne = new Buffer(8);
// Uninitalized buffer and contains 8 bytes
var bufferTwo = new Buffer([ 8, 6, 7]);
//This initializes the buffer to the contents of this array. The array are integers representing bytes.
var bufferThree = new Buffer("This is a string", "utf-8")
// This initializes the buffer to a binary encoding of the first string as specified by the second argument (in this case, utf-8).
30. How to test your code in Node.js
The assert
module in Node.js provides easy way of writing test in a limited ways. It provides no feedback when running your tests unless one fails. It provides 11 methods to test our code to check it is working as we expect. Some of them are: assert.equal
, assert.deepEqual
, assert.throws
.
assert.equal(2 + 2, 4, 'two plus two is four');
Other than this, we can use testing frameworks like, mocha
, chai
and karma
.
31. What is the difference between setImmiediate
vs nextTick
We should use setImmediate
if we want to queue the function behind whatever I/O event callbacks that are already in the event queue. And we use process.nextTick
to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.
As per node.js documentation, “nextTickQueue
will be processed after the current operation completes, regardless of the current phase of the event loop.” It means, this queue will be executed whenever the boundary between JavaScript and C/C++ is crossed.
The below code contains setTimeout
, setImmiediate
and nextTick
:
import fs from 'fs';
import http from 'http';
const options = {
host: 'www.stackoverflow.com',
port: 80,
path: '/index.html'
};
describe('deferredExecution', () => {
it('deferredExecution', (done) => {
console.log('Start');
setTimeout(() => console.log('TO1'), 0);
setImmediate(() => console.log('IM1'));
process.nextTick(() => console.log('NT1'));
setImmediate(() => console.log('IM2'));
process.nextTick(() => console.log('NT2'));
http.get(options, () => console.log('IO1'));
fs.readdir(process.cwd(), () => console.log('IO2'));
setImmediate(() => console.log('IM3'));
process.nextTick(() => console.log('NT3'));
setImmediate(() => console.log('IM4'));
fs.readdir(process.cwd(), () => console.log('IO3'));
console.log('Done');
setTimeout(done, 1500);
});
});
will give the following output.
Start
Done
NT1
NT2
NT3
TO1
IO2
IO3
IM1
IM2
IM3
IM4
IO1
32. What is blocking and nonblocking API in Node.js and how does it affect the architecture of your applications
Blocking is when the execution of JavaScript in the Node.js process must wait until a non-JavaScript operation completes. This happens because the event loop is unable to continue running JavaScript while a blocking operation is occurring. Synchronous methods in the Node.js standard library that use libuv are the most commonly used blocking operations.
To simply put, Blocking methods execute synchronously and non-blocking methods execute asynchronously.
The following example reads a file from File System synchronously.
const fs = require('fs');
const data = fs.readFileSync('/myfile.txt'); // blocks here until file is read
Here is the same operation but reads the file asynchronously.
const fs = require('fs');
fs.readFile('/myfile.txt', (err, data) => {
if (err) throw err;
});
Althought the first example is simpler than the second, it has a disadvantage of blocking the execution of additional JavaScript until the entire file is read. Also if an error is thrown it will need to be caught or the process will crash. In the asynchronous version, it is up to us to decide whether an error should throw.
33. Why do you use forever
with Node.js ?
forever
is a node.js package that is used to keep the server alive even when the server crash/stops. When the node server is stopped because of some error, exception, etc. forever automatically restarts it.
Forever can be used as
forever start app.js
Finally, the purpose of forever
is to keep a child process (such as our node.js web server) running continuously and automatically restart it when it exits unexpectedly. forever
has some default options and configuration convention as follow:
forever
keeps track of running processes in*.fvr
files that are placed in/tmp/forever/pids
- Each
forever
process will generate a unique log file placed in/tmp/forever/*.log
- Unless otherwise specified, the output of the child process’
stdout
andstderr
will be written to the above log file.
34. What are the main advantages and disadvantages of using Node.js
Some of the advantages of Node.js are:
- Easy to Learn: As JavaScript is one of the most popular programming languages for front-end development, nearly every front-end developer is familiar with this universal language. Therefore, it is much easier to switch to using Node.js at the back-end.
- More Freedom: Unlike some backend like Ruby on Rails which is a framework that imposes rules and guidelines of developing software in a particular way, Node.js gives much more space and freedom in doing it our own way. Node.js is completely unopinionated, meaning we can start building everything from scratch.
- Simultaneous Request Handling: Node.js provides the non-blocking IO system that enable us process numerous requests concurrently. The system makes simultaneous request handling much better than in other languages like Ruby or Python.
- Rich Community: The Node.js developers community is a very active and vibrant group of developers who contribute to constant improvement of Node.js.
Some of the disadvantages are:
- Unstable API and Inconsistencies: One of the biggest disadvantages of Node.js is that it lacks consistency. Node.js’ API changes frequently, and the changes are often backward-incompatible.
- Not Suitable for Heavy-Computing Apps: Node.js doesn’t support multi-threaded programming yet. It is able to serve way more complicated applications than Ruby, but it’s not suitable for performing long-running calculations.
- Event Driven Model: Event driven model will confuse a lot of programmers who are new to JavaScript. The callback chain can get very long which makes it harder to maintain.
35. What are the types of applications that can be built by using Node.js
- If we need an application should be realtime, then Node.js is best suitable. Because it have the best supporting library Socket.IO based on websockets.
- If we need a Single Page Application, Node.js is definite go here. Because MEAN stack is most popular stack for single page applications.
- When we want to stream the data, then go with node.js, because it’s good at handling i/o.
- When we want our project to be a single language from back end to front end. Then go with node.js, its completely in JavaScript.
36. Why Node.js is based on single threaded architecture
Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.
A node.js app that isn’t doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.
Also, V8 is a single threaded execution engine. It’s built to run exactly one thread per JavaScript execution context. We can run two V8 engines in the same process, but they won’t share any variables like real threads.
37. What are the different types of APIs available in Node.js
Node.js provides lot of API out of the box. Some of them are:
- File System API or
fs
for interacting with the file system. http
API for using HTTP server.child_process
API for spawning child processes.crypto
module provides cryptographic functionalityevents
for event-driven programming.os
module provides a number of operating system-related utility methods.v8
module exposes APIs that are specific to the version of V8 built into the Node.js binary.
38. How can we handle blocking I/O operations in Node.js
Yes, Node can be run on Windows, macOS, many “flavours” of Linux, Docker, etc.
For the uninitiated, MAX_PATH
is a limitation with many Windows tools and APIs that sets the maximum path character length to 260 characters. There are some workarounds involving UNC paths, but unfortunately not all APIs support it, and that’s not the default. This can be problematic when working with Node modules because dependencies are often installed in a nested manner.
39. What is the difference between Node.js and AngularJS
Both frameworks are built with JavaScript.
AngularJS is a JavaScript framework. It is open source web application framework mainly maintained by Google. It is a front-end framework mainly used to create Single Page Applications. It follows MVC architecture.
On the other hand, Node.js is a cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript and can be run within the Node.js runtime. It also provides a rich library of various JavaScript modules which simplifies the development of web applications to a great extent.
Angular and node are Both the open-source tools as node.js is mainly used to build server-side applications, whereas AngularJS is suited for building single-page client-side web applications both can be combined to create isomorphic web applications, i.e. applications that are built with the same language on the back and front-ends, but they are quite different in their architecture and working.
40. How will you import external libraries in Node.js
If it is an npm
module, we can install it by running npm install library
. We can import using const library = require('library')
whereever we needed.
When we requires a module in nodejs, the content of module.exports
is returned.