Share this:

173 Frequently asked Node JS Interview Questions

1. What is Node.JS?
Answer: Node.js is an open-source, cross-platform JavaScript run time environment for  server side scripting  built on Chrome/Google’s V8 JavaScript engine. It uses an event-driven, non-blocking I/O model.

2. What is application of Node.JS?
Answer: Node.Js can be used to develop following
1.I/O intensive web applications like video streaming sites.
2.Single-page applications.
3.Real-time web/chat applications.
4.It can be used for Network applications.
5.General-purpose applications
6.Distributed systems.

3. What are Most Popular JavaScript Engine?
Answer: Google Chrome – V8 // Fastest JavaScript Engine

Mozilla FireFox – SpiderMonkey

Microsoft Edge – Chakra

4. What are the features of Node.js?
Answer: Features of Node.JS

1. Asynchronous and Event Driven and non blocking I/O
2. Very Fast Execution
3. Single Threaded  but highly scalable
4. Node Package Manager(NPM)
5. An Active and vibrant community for the Node.js framework Which  keeps the framework updated with the latest trends in the web development.
6. No Buffering
7. Node.js library uses Javascript
8. It is open sourced.

5. In which Language Node.js is Written?
Answer: Node.js is written in C‎, ‎C++‎, ‎JavaScript .

6. Who is the author of Node Js ?
Answer: Node Js is written by Ryan Dahl in 2009.

7. Why do we use Node.js?
Answer: Node.JS is use for the following reason
1.It is very fast.
2.It almost never blocks .
3.It offers a unified programming language and data type. It provides an easy way to build scalable network programs.
4.Everything is asynchronous.
5. It yields great concurrency.

8. What is the latest version of Node.js?
Answer: Latest version of Node.js is – v0.10.36.

9. Why is Node.js Single-threaded?
Answer: Node Js is single threaded for performing asynchronous process.  A single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation by doing asynchronous processing on.

10. How to Install Node.JS?
Answer: Installation Steps

  1. Download the Windows installer and binary files from the Nodejs.org web site.
  2. Run the installer (the .msi file downloaded in the previous step.)
  3. Accept the license agreement by clicking the NEXT button as many times is popping up. And accept the default installation settings as per the prompt in the installer.
  4.  Restart the computer to run Node.js.

11. What is the relation of Node.JS with JavaScript?
 Answer: Node.JS allows the developers to create new modules in JavaScript.

It is a virtual machine that leverages JavaScript as its scripting language to achieve high output.

12. What is NPM ?
Answer: NPM stands for Node Package Manager. It is used to provide command line environment to install and manage Node.JS Packages, and Node.JS repositories that can be accessed at search.nodejs.org.

Code Source
npm install express –save

Non  install lodash –save

13. How to check globally installed dependencies using NPM?
Answer: globally installed dependencies can be checked using NPM
code source
npm ls — g

14. What is NVM?
Answer: NVM stands for Node Version Manager,  NVM can be used to change node.js versions very easily. This is very helpful to work on multiple projects of Node.js having different versions, etc.

15. How to uninstall a dependency using npm?
Answer:
uninstall a depedency using npm
code source

npm uninstall dependency-name

16. How to update dependency using npm?
Answer:       update depedency using npm
code source
.        npm  update [-g] [<pkg>…]

npm update
.        </pkg>

17. How to update NPM to a new version in Node.js?
Answer: The following commands are used to update NPM to a new version:

$ sudo npm install npm -g

/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js

npm@2.7.1 /usr/lib/node_modules/npm

18. What is Modules in Node.Js ?
Answer: Modules in node.js are block of code whose existence does not impact other code in any way and it can be reused throughout the Node.js application. It is introduced in ES6 and important for Maintainability, Reusability, and Namespacing of Code.

19. What is the use of require() in Node Js ?
Answer: require() is a function to include a module in Node from external files. It takes a string parameter which contains the location of the file that you want to include. require reads the entire javascript file, executes the file, and then proceeds to return the exports object.

Syntax:

require(‘path’);

20. Explain event loop in Node.Js
Answer: In node.Js, an event loop is a mechanism that allows Node.js to perform non-blocking I/O operations.
It handles all async callbacks. Node.js is a single-threaded, event-driven language. This means a listeners to events, and when a event fires, the listener can be attached to an event to executes the callback provided.

Whenever setTimeout, http.get  ,  and , fs.readFile are called, Node.js runs this operations and further continue to run other code without waiting for the output. At the end of the operation, it receives the output and runs callback function.Therefore all the callback functions are queued in an loop, and will run one-by-one when the response has been received.

21. Mention the framework which is commonly used in node.js?
Answer: Express is the commonly used framework used in node.js.

22. What are the API functions in Node.js ?
Answer: The API functions in Node.js are

  1. a)Synchronous, blocking functionsb) Asynchronous, non-blocking functions

23. Why node.js is  gaining attention from JAVA programmers?
Answer: Node.js is  gaining attention because it is a loop based server for JavaScript. Node.js provides user the ability to write the JavaScript on the server, which has access to  HTTP stack, file I/O, TCP and databases.

24. Mention the steps to async in Node.js?
Answer: Following are the steps to async in Node.js

1)      First class functions

2)      Function composition

3)      Callback Counters

4)      Event loops

25. What is Nodemon?
Answer: Nodemon is a utility that will monitor any changes in the source code and automatically restart the server. It is the best tool that  can be used, while developing any node.js project. It can be installed by using NPM.
nodemon can be also installed  as a development dependency:
code source
npm install nodemon –save-dev

code source
nodemon [node app]

26. What is REPL in Node.js?
Answer: In Node.js REPL means “Read Eval Print Loop”. REPL is a program that accepts the commands, evaluates them, and finally prints the results. It provides an environment similar to that of Unix/Linux shell or a window console.

27. What are the functions performed by REPL?
 Answer: REPL performs the following functions

  1. READ: Reads the input from the user, parses it into JavaScript data structure and then stores it in the memory.
  2. EVAL: Executes the data structure.
  3. PRINT: Prints the result obtained after evaluating the command.

            4.LOOP: Loops the above command until the user presses     Ctrl+C two times.

28. Syntax to install modules using NPM.
Answer: Syntax to install : $ npm install

$ npm install express

var express = (‘express’);
Name of the module is express, and express is JS file, that can be used in the module.

29. How Node.js solves the problem of blocking of I/O operations?
Answer: Node.js has an event based model at its core to solve problem of blocking of I/O Operations. Node.js uses an event loop instead of threads.

30. What are the Challenges with Node.js ?
Answer: Challenges in Node.js is to have one process with one thread to scale up on multi core server.

31. What is the fundamental difference between Node.js and Ajax?
Answer: Ajax is designed for client side technology to dynamically update a particular section of a page’s content, without having to update the entire page.

Node.js is build for developing client-server applications in server side JavaScript environment.

32. What is I/O in the context of Node.js?
Answer: I/O (Input and Output) is used to access anything outside of the application and gets loaded on to the machine memory in order to run programs after the application is fired up.

33. Explain  Promises.
Answer: Promises are a concurrency primitive and  they are the part of most modern programming languages to help in handling async operations.

34. What is chaining in node.js?
Answer: Chaining in node.js is a procedure where the output of one stream is connected to another stream that is in turn creates a chain of multiple stream operations.

35. When are background/worker processes useful? How can you handle worker tasks?
Answer: Worker processes are very useful to perform data processing in the background for sending out emails or processing images. RabbitMQ or Kafka are option for handling worker tasks.

36. What is the difference between Asynchronous and Non-blocking?
Answer: Asynchronous means while requesting, we are not waiting for the server response and continue with other block and respond to the server response when we received.

Non-Blocking is used generally with Input-Output (IO).

37. What is Tracing in Node.js?
Answer: Tracing is a mechanism to collect tracing information generated by V8, Node core and userspace code in a log file. Tracing are enabled by passing the –trace-events-enabled flag.
While Running Node.js with enabled tracing will produce log files that will be opened in the chrome://tracing  tab of Chrome.

38. What is callback in Node.js?
Answer: A callback function allows other code to be run in the meantime and prevents any blocking.  Node.js relies on callback because Node.js is an asynchronous platform.

Using Callback function node.js can deal with multiple requests made to the server.  If there is a large file which is going to take a long time for a server to read and don’t want a server to get engage in reading that large file while dealing with other requests, call back function is used. It allows the server to deal with pending request first and call the function when it is finished.

39. What is the command used in node.js to import external libraries?
Answer: External libraries can import using  command  “require” in node.js.
Example:
var http=require (“http”)
It will load the http library . The single exported object through the http variable.

40. What are the pros and cons of Node.js?
Answer: Pros:

1)  A application which does not have any CPU intensive computation, can be built in Javascript top to bottom, even down to the database level  by using JSON storage object DB such as MongoDB.

2) Crawlers receive a full-rendered HTML response, which is  more SEO friendly than a single page application or a websockets app run on top of Node.js.

Cons:

1) Node.js responsiveness can be blocked by intensive CPU computation , therefore a threaded platform is a better approach.

2) Relational databases with Node.js are less favourable.

41. What is control flow function?
Answer: Control flow function are generic piece of code which runs in between several asynchronous function calls.
The steps are 1) Control the order of execution, 2) Collect data, 3) Limit concurrency, and 4) Call the next step in the program.

42. How node.js works?
Answer: Node.js is a virtual machine that utilizes JavaScript as its scripting language and it works on a v8 environment. It achieves high output via non-blocking I/O and single threaded event loop.

43. Explain some features of Express JS.
Answer: Following are main features of Express JS

1. It provides a response to the HTTP or RESTful requests.
2.The routing table can be defined for performing various HTTP operations with the help of express JS.

  1. It can be used for dynamically rendering HTML pages that are based on passing arguments to the templates.
  2. It provides similar features which are provided by core Node JS.
  3. The presence of a thin layer prepared by the Express JS makes the performance of Express JS adequate.
    6.To organise the web applications into the MVC architecture it can be used. Routes to rendering view and performing HTTP requests can be managed and handled by Express JS.

44. What is Express JS?
Answer: Express JS is a JavaScript framework  used for the development of mobile as well as web applications with the help of node JS. It is a light-weighted node JS which has a number of flexible, useful and important features. Express JS helps in organizing the web application into MVC architecture on the server side.

45. What’s the difference between ‘front-end’ and ‘back-end’ development?
Answer: Front-end is concerned with the client (user) side of the webpage.  back-end is focused on the processes happening in the background  which clients don’t see.

46. How can models be defined in Express JS?
Answer: The concept of models is left up to third-party node modules because there is no notion of any database. It allows the users to interface with nearly any type of database.

47. Why to use Express.js?
Answer: Following are the reason to use the Express JS with Node Js

1.It is the better choice framework for ultra-fast Input / Output.

2.Cross Platform and Support MVC Design pattern

3.Support of NoSQL databases out of the box.

  1. Multiple templating engine support like Jade or EJS which reduces the amount of HTML code.
  2. basic web-server creation, and easy routing tools.

48. How to make post request in Node.js?
Answer: The code snippet can be used to make a Post Request in Node.js.

var request = require(‘request’);

request.post(

‘http://www.example.com/action’,

{ form: { key: ‘value’ } },

function (error, response, body) {

if (!error && response.statusCode == 200) {

console.log(body)

}

}

);

49. How do you avoid callback hells?
Answer: The issue of callback hells can be avoided as following

  1. usegenerators with Promises1
    2.
    modularization: break callbacks into independent functions
    3. use acontrol flow library, like async.

 

50. What are the timing features of Node.js?
Answer: In Node.js, the timer module contains functions that execute code after a set period of time.

  1. setTimeout/clearTimeout– used for scheduling code execution after a designated amount of milliseconds.
  2. setInterval/clearInterval– used for executing a block of code multiple times
  3. setImmediate/clearImmediate– used for executing code at the end of the current event loop cycle
  4. nextTick– used for scheduling a callback function to be invoked in the next iteration of the Event Loop

function cb(){

console.log(‘Processed in next iteration’);

}

process.nextTick(cb);

console.log(‘Processed in the first iteration’);

Output:

Processed in the first iteration

Processed in next iteration

 

51. Explain Reactor Pattern in Node.js?
Answer: Reactor Pattern pattern provides a handler that is associated with each I/O operation. After an I/O request is generated, it is submitted to a demultiplexer which is a notification interface to handle concurrency in non-blocking I/O mode and collects every request in form of an event. This queues each event in a queue. Thus,  Event Queue are provided by the demultiplexer.

There is an Event Loop which iterates over the items in the Event Queue,  it has a callback function associated with it, and that callback function is invoked when the Event Loop iterates.

 

52. What is LTS releases of Node.js ?
Answer: LTS stands for Long Term Support. An LTS(Long Term Support) version of Node.js supports the critical bug fixes, security updates and performance improvements.

 

53. Explain ECMAScript ?
Answer: ECMAScript is used for client-side scripting on the World Wide Web and used by Node Js for writing server applications and services and it standardise Javascript.

 

54. List out some REPL commands in Node.js?
Answer:
Following are the list of REPL commands inNode.Js

Ctrl + c : For ending the current command.

Ctrl + c twice : To terminate REPL.

Ctrl + d : To terminate REPL.

Tab Keys : list all the current commands.

.break :To  exit from multiline expression.
.save with filename :To save REPL session to a file.

Command : ctrl + c twice It is used to stop REPL.

 

55. How Control Flow controls the functions calls?
Answer:
Following are the steps to controls function calls

1)      Control the order of execution.

2)      Collect data.

3)      Limit concurrency.

4)      Call the next step in program.

56. Can we access DOM in node?
Answer: We cannot access DOM in node.

57. List the two arguments which async.queue takes?
Answer: The two arguments which async.queue takes – Task function and Concurrency value.

58. Explain where to choose Node.js and where to avoid node.js?
Answer: we choose node.js in following cases

  • js can be used for developing streaming or event-based real-time applications that require less CPU usage like Chat applications and Game servers.
  • js can be a good choice for fast and high-performance servers, which need to handle thousands of user requests simultaneously.
  • It is suitable for collaborative environments that means where multiple people work together. Node.js has an event loop feature. js enables it to handle multiple events simultaneously without getting blocked Example for advertisement servers and streaming servers.

Node.js is a good choice when we need high levels of concurrency but less amount of dedicated CPU time.

Following are the cases where node.js should be avoided

We should not use it for cases where the application requires long processing time because it is a single threaded framework.

59. List out IDEs can be  used for Node.js development?
Answer: Following are the list of most commonly used IDEs for developing node.js applications.

Cloud9.

It is a free, cloud-based IDE provides a powerful online code editor that enables a developer to write, run and debug the app code and supports, application development, using popular programming languages such as Node.js, PHP, C++, Meteor etc.
JetBrains WebStorm.

Webstorm IDE provides features like intelligent code completion, navigation, automated and safe refactorings. We can also use the debugger, VCS, terminal and other tools present in the IDE.

JetBrains InteliJ IDEA.

It supports web application development using mainstream technologies like Node.js, Angular.js, JavaScript, HTML5  provides features including syntax highlighting, code assistance, code completion and more. We have to install a Node.js plugin for  enabling the IDE that can do Node.js development.

Komodo IDE.
It is a cross-platform IDE to provides a variety of features, like keyboard shortcuts, collapsible Pane, workspace, auto indenting, code folding and code preview using built-in browser.

Eclipse.

It is a cloud-based IDE for web development using Java, PHP, C++  etc. The features of Eclipse IDE can be availed by using the Node.js plug-in, which is <nodeclipse>.

Atom.

It is an open source application that works on top of Electron framework to develop cross-platform apps using web technologies. It built with the integration of HTML, JavaScript, CSS, and Node.js.

60. How to get post data in Node.js?
Answer: Code snippet to fetch Post Data:

app.use(express.bodyParser());

app.post(‘/’, function(request, response){

console.log(request.body.user);

});

 

61. What is callback hell in Node.js?
Answer: Callback hell is created when heavily nested callbacks that make code unreadable and difficult to maintain. This kind of situation mainly occurs while doing heavy calculation of data/fetching complex data.

 

62. Explain the code to create HTTP Server in Nodejs.
Answer: <http-server> is the code to create HTTP server.

Sample code

var http = require(‘http’);

var requestListener = function (request, response) {

response.writeHead(200, {‘Content-Type’: ‘text/plain’});

response.end(‘Welcome Viewers\n’);

}

var server = http.createServer(requestListener);

server.listen(8080); // The port to start with

 

63. What Are Globals In Node.js?
Answer: Global, Process, and Buffer are three keywords in Node.js which constitute as Globals.

Global

The Global keyword acts as a container for all other <global> objects.

<console.log(global)>,  print out all.

Process

Process is  also the global objects but includes additional functionality to turn a synchronous function into an async callback.
It provides the information about the application or the environment.

  • <process.execPath> – For receiving the execution path of the Node app.
  • <process.Version> – For receiving the Node version currently running.
  • <process.platform> – For receiving the server platform.

Useful process methods are following

  • <process.memoryUsage> – provides the memory used by Node application.
  • <process.NextTick> – For attaching a callback function that will get called during the next loop.

Buffer

It is a class in Node.js to handle binary data and It is similar to a list of integers. Buffer stores as a raw memory outside the V8 heap.

JavaScript string objects can be converted into Buffers.
1.Specifies 7-bit ASCII data.-<ascii>
2.Represents multibyte encoded Unicode char set.- <utf8>
3.Indicates 2 or 4 bytes, little endian encoded Unicode chars.-<utf16le>
4.Used for Base64 string encoding.-<base64>
5.Encodes each byte as two hexadecimal chars.-<hex>
The syntax to use the Buffer class.

> var buffer = new Buffer(string, [encoding]);

To write a <string> to an existing buffer object, use the following line of code.

> buffer.write(string)

64. How to load HTML in Node.js?
Answer: We have to change the “Content-type” in the HTML code from text/plain to text/html to load HTML in Node.js.

65. What is EventEmitter in Node.js?
Answer: The Event module in Node.js contains “EventEmitter” class which is  used to raise and handle custom events.
Following code is to access it.

// Import events module

var events = require(‘events’);

// Create an eventEmitter object

var eventEmitter = new events.EventEmitter();

The “on” property of EventEmitter is used to bind a function to the event and “emit” property of EventEmitter is used to fire an event.

66. List the types of Streams are present in Node.js?
Answer: Stream are objects  which permit reading data from a source or writing data to a specific destination in a continuous fashion in Node.js .

There are four types of streams in Node.js

  1.  Used for reading operation.-<Readable>
  2. Used for the write operation.-<Writable>
  3. Used for both the read and write operations.- <Duplex>
  4. Performs the computations based on the available input.-<Transform>

 

67. What is the Global Installation of Dependencies?
Answer: Globally installed packages/dependencies can be used in CLI (Command Line Interface) function of any node.js, but cannot be imported using require() in the Node application directly.

Node project can be installed globally using -g flag as.

 

68. What is the Local Installation of Dependencies?
Answer: NPM installs any dependency in the local mode means that any package gets installed in “node_modules” directory which is present in the same folder with Node application.
Syntex to install a Node project locally

C:\Nodejs_WorkSpace>npm install express

 

69. What is Package.json?
Answer: Package.json contains all metadata information about Node.js Project or application. It is locate in the root directory of every Node.js Package or Module. It describes metadata of the module in JSON format.
<package.json> file are use in NPM (Node Package Manager).
Name, version,  author and dependency are some important attributes of package.json.

70. Does Node.js support Multi-Core platforms and is it capable of utilising all the cores?
Answer: Node.js is by default a single-threaded application, But it can facilitate deployment on multi-core systems where it does use the additional hardware. It packages with a Cluster module which is enable of starting multiple Node.js worker processes which will share the same port.
Node.js can’t utlizes all the cores of the multi-core system.

71. Which is the First Argument usually passed to a Node.js callback handler?
Answer: Usually the first argument is an optional error object in Node.js and if there is no error, then the argument defaults to null or undefined.

Following is an example of signature for the Node.js callback handler.

function callback(error, results) {

// Check for errors before handling results.

if ( error ) {

// Handle error and return.

}

// No error, continue with callback handling.

}

72. What is the difference between Nodejs and JQuery?
Answer: Though Node.js, jQuery both are the advanced implementation of JavaScript. But they serve completely different purposes.

Node.js

To develop a client-server applications, Node.js is a server-side platform. For example Node.js can build online employee management system as it runs on a server similar to Apache, Django not in a browser but it can’t be done in client-side Js .

JQuery

JQuery is also a JavaScript module which complements AJAX, DOM traversal, looping and so on. This library provides many useful functions to help in JavaScript development and it manages cross-browser compatibility, Therefore it can help in producing highly maintainable web applications.

73. What is A Child_process Module in Node.js?
Answer: Child processes are created in node.js to help in parallel processing along with the event-driven model.

The Child processes have three streams <child.stdin>, <child.stdout>, and <child.stderr>.
The streams of the child process are shared by <stdio> stream of the parent process.

Following are three methods to create a child process

  1. method runs a command in a shell/console and buffers the output.- exec – <child_process.exec>
  2. launches a new process with a given command-spawn – <child_process.spawn>

It is a special case of the spawn() method to create child processes.-fork – <child_process.fork>

74. What are Node.js web application architecture?
Answer: Web application has 4 layers as described below

1. Client Layer: Web browsers, mobile browsers or applications which can make an HTTP request to the web server are contained in client layer.

2. Server Layer: The Web server are contained in the server layer which can intercept the request made by clients and pass them the response.

3. Business Layer: Application server which is utilised by the web server to do required processing business layer. This layer communicate with the data layer via database or some external programs.

4.Data Layer: Databases or any source of data are contained in Data layer.

Node.js web application architecture

75. Mention few types of npm modules.
Answer: Express, connect, socket.io and socketjs, pug, mongodb and mongojs, redis, lodash, forever, bluebird are few types of bpm modules.

76. Does Node.js provide Debugger?
Answer: Debgger in Node.js are a simple TCP based protocol which built-in debugging client. To debug a JavaScript file,  debug argument can be used followed by the js file name  to be debugged.
Syntex: node debug [script.js | -e “script” | <host>:<port>]

77. What tools are used to assure a consistent style in Node.js?
Answer: JSLint ,JSHint ,ESLint are JSCS tools to be used to assure a consistent style in Node.js.

78. What are the differences between operational and programmer errors?
Answer: Operational errors create problems with the system like request timeout or hardware failure though its not a bug. Programmer errors are real bugs.

79. Can we evaluate simple expressions using Node REPL?
Yes, We can evaluate simple expression using REPL.

80. What is the application of the underscore variable in REPL?
Answer: Underscore variables are used to get last result in REPL.
Example
C:\Nodejs_WorkSpace>node

> var x = 5

undefined

> var y = 6

undefined

> x + y

11

> var sum = _

undefined

> console.log(sum)

11

undefined

            >

81. cryptography is supported byNode.js?
Answer: Node.js has a Crypto module which supports cryptography. Crypto module provides cryptographic functionality which includes a set of wrappers for open SSL’s hash HMAC, cipher, decipher, sign and verify functions.

Example
    const crypto = require(‘crypto’);

const secret = ‘abcdefg’;

const hash = crypto.createHmac(‘sha256’, secret)
.update(‘Welcome to JavaTpoint’)
.digest(‘hex’);
console.log(hash);

82. What is the role of assert in Node.js?
Answer: The Node.js Assert is used to write tests and provides no feedback when running the test unless one fails. It provides a simple set of assertion tests which can be used to test invariants. The module is  for internal use by Node.js, but can be used in application code via require (‘assert’).
Example

var assert = require(‘assert’);

function add (x, y) {

return x + y;

}

var expected = add(1,3);

assert( expected === 4, ‘one plus three is four);

83. What is the difference between events and callbacks in Node.js?
Answer: Callback function is called when an asynchronous function returns its result whereas event handling is work on the observer pattern.

84. What is the Punycode in Node.js?
Answer: Punycode is used to convert Unicode (UTF-8) string of characters to ASCII string of characters which is bundled with Node.js v0.6.2 and later versions.  To use it with other Node.js versions, use npm to install Punycode module first.  access it use require (‘Punycode’).
syntex

punycode = require(‘punycode’);

85. What does Node.js TTY module contains?
Answer: The Node.js TTY module has tty.ReadStream and tty.WriteStream classes. To access this module, we have to use require (‘tty’).

Syntex
var tty = require(‘tty’);

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

Answer: A module contains related code into a single unit of code and it can be interpreted as moving all related functions into a file. module.exports  exposes functions to the outer world. We can import them in another file as well.

87. What are the differences between setImmediate() vs setTimeout()?
Answer: setImmediate() executes a script once the current poll (event loop) phase completes.

setTimeout() designed to schedule a script to be run after a minimum threshold ( in ms) has been elapsed.

88. What is process.nextTick()?
Answer: After completion of  the current operation, the nextTickQueue will be processed regardless of the current phase of the event loop.

All callbacks passed to process.nextTick() will be resolved before the event loop continues whenever  process.nextTick() are called in a given phase.

89. What is libuv?
Answer: In node.js libuv is a multi-platform support library with the focus on asynchronous Input/Output and features of libuv are:
1. Fully featured Event loop, backed by epoll, kqueue, IOCP, event ports.
2.Asynchronous TCP and UDP sockets,
3. Asynchronous file and file system operations,

4.Child processes,
5.File system events

90. What are some of the most popular modules of Node.js?
Answer: express, async, browserify, socket.io, bower, gulp, grunt are most starred or most downloaded modules in Node.js.

91. What are the differences between readFile vs createReadStream in Node.js?
Answer: readFile asynchronously reads the entire contents of a file and will read the file completely into memory before making it available to the User. createReadStream will read the file in chunks of the default size 64 kb which is specified before hand.

92. What is the use of Timers is Node.js?
Answer: In Node.js the Timers module contains functions that execute code after a set period of time. Node.js Timer are setTimeout(), setImmediate() and setInterval.

93. What are the uses of DNS module in Node.js?
Answer: In node.js dns module provides underlying system’s name resolution and DNS look up facilities.
Following are the functions in DNS module:

  1. dns.lookup(adress, options, callback) – The dns function can take any website address as its first parameter and returns the corresponding first IPV4 or IPV6 record.  If no options are given both IPV4 and IPV6 are valid inputs and the third parameter is the callback functions.
  2. dns.lookupservice(address, port, callback) – This function can convert any physical address such as “www.xxxxx.com” to array of record types.
  3. dns.getServers() – This function can return an array of IP address strings, formatted according to rfc5952, which are currently configured for DNS resolution.
  4. dns.setServers() – This function can set the IP address and port of servers to be used when performing DNS resolution. The dns.setServers() method should not be called while a DNS query is in progress.

94. What is the security mechanisms available in Node.js?
Answer: Following are the security mechanism in Node.js:
Authentication — In Node.js, authentication are session-based or token-based. The user’s credentials are compared to the user account stored on the server and, in the event of successful validation, a session is started for the user in session-based authentication. The user’s credentials are applied to generate a string called a token which is then associated with the user’s requests to the server in token-based authentication.

Error Handling — The error message contains the explanation of error. when the errors are in application code syntax, it can be set to display the entire log content on the frontend. The error log content can reveal a lot of sensitive internal information about the application code structure and tools used within the software for an experienced hacker.

Request Validation —  An additional measure of securing Node.js Application can validate the incoming data types and formats and rejecting requests not conforming to the set rules.

helmet (set HTTP headers to protect application ), node rate limiter (controls the rate of repeated requests), csurf (validates tokens in incoming requests and rejects the invalid ones), and cors (enables cross-origin resource sharing) are available tools.

95.What is the passport in Node.js?
Answer: In node.js, Passport.js is a simple, unobtrusive authentication middleware. Passport can recognize that each application has unique authentication requirements. Passport responds with a 401 Unauthorized status, and any additional route handlers shall not be invoked, if authentication fails. The next handler will be invoked, If authentication succeeds.

96. Write the below JavaScript code in another ways using Node.Js to produce the same output?
Answer: console.log(“one”);

setTimeout(function() {

console.log(“two”);

}, 0);

console.log(“three”);

 

Output:

one

two

three

 

setImmediate(fn) can be used in place of setTimeout(fn,0) in Node.js version 0.10 or higher,because it is faster.
Following is the code

console.log(“one”);

setImmediate(function()
{

console.log(“two”);

});

console.log(“three”);

97. How to update NPM to a new version in Node.js?
Answer: The following is the commands to update NPM to a new version:

$ sudo npm install npm -g

/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js

npm@2.7.1 /usr/lib/node_modules/npm

 


98. Which is the first argument typically passed to a Node.js callback handler?

Answer: The first argument to any callback handler is an optional error object and it can be null or undefined if there is no error.

99. What are exit codes in Node.js? List some exit codes.
Answer: The specific codes which are used to end a “process” (a global object used to represent a node process) is called exit codes.
Unused,  Uncaught Fatal Exception,Fatal Error, Non-function Internal Exception Handler, Internal Exception handler Run-Time Failure and Internal JavaScript Evaluation Failure are some example of exit code.

100. What is the difference between AngularJS and Node.js?
Answer: Node.js is a runtime system and Angular.JS is a web application development framework.

101. Why is consistent style important?
Answer: Consistent style modify projects easily without having to get used to a new style every time.

102. What is a stub?
Answer: Stubs are functions which simulate the behaviours of modules. Stubs gives canned answers to function calls made during test cases.

Example
var
fs = require(‘fs’)

var writeFileStub = sinon.stub(fs, ‘writeFile’, function (path, data, cb) {

return cb(null)

})

expect(writeFileStub).to.be.called

writeFileStub.restore()

103. What’s a test pyramid?
Answer: A test pyramid explain the ratio of how many unit tests, integration tests and end-to-end test should be written.

104. When are background/worker processes useful?
Answer: Background/Worker processes are extremely useful for doing data processing in the background, such as sending emails or processing images.

There are options like RabbitMQ or Kafka.

105. How can we secure HTTP cookies against XSS attacks?
Answer: XSS attacks occurs when the attacker injects executable JavaScript code into the HTML response.

To secure HTTP from these attacks, we have to set flags on the set-cookie HTTP header:

HttpOnly–  Used to prevent attacks such as cross-site scripting because it does not allow the cookie to be accessed via JavaScript.
secure– Tells the browser to only send the cookie if the request is being sent over HTTPS.

106. What is wrong with the code snippet?
Answer: new Promise((resolve, reject) => {

throw new Error(‘error’)

}).then(console.log)

Since there is no catch after the then. The error will be a silent one with no indication of an error thrown.

It can be fixed by
new Promise((resolve, reject) => {

throw new Error(‘error’)

}).then(console.log).catch(console.error)

To debug a huge codebase, we can use the unhandledRejection hook which will print out all unhandled Promise rejections.

process.on(‘unhandledRejection’, (err) => {

console.log(err)

})

107. What is wrong with the following code snippet?
Answer: function checkApiKey (apiKeyFromDb, apiKeyReceived) {

if (apiKeyFromDb === apiKeyReceived) {

return true

}

return false

}

This syntex is  vulnerable to timing attacks because it has no fixed time to compare.

To solve the issue, we can use the npm module called cryptiles.

function checkApiKey (apiKeyFromDb, apiKeyReceived) {

return cryptiles.fixedTimeComparison(apiKeyFromDb, apiKeyReceived)

}

108. What are the parameters passed for Child process module?
Answer: Following are parameters passed for Child Process Module

child_process.exec(command[, options], callback)

command – command to run with space-separated arguments.

options – object array which comprises one or more options like cwd , uid, gid, killSignal, maxBuffer, encoding, env, shell, timeout

callback –  function which gets 2 arguments like stdout, stderr and error.

109.  Explain Piping Stream?
Answer: Piping stream means  mechanism of connecting one stream to other.  It is used for receiving the data from one stream and pass the output to other stream. There are not any limit for piping stream.

110. Explain FS module ?
Answer: FS module is used for File I/O where FS stands for “File System” .  This module can be imported in the following way :var test = require(“fs”)

111. Explain console.log([data][, …]) statement in Node.JS?
Answer: The statement is used to print to “stdout” with newline and the function can take multiple arguments as “printf()”.

112. What are the properties of process?
Answer: Following are the useful properties of process –

  1. Platform
  2. Stdin
  3. Stdout
  4. Stderr
  5. execPath
  6. mainModule
  7. execArgv
  8. config
  9. arch
  10. title
  11. version
  12. .argv
  13. env
  14. exitCode

113. Define OS module?
Answer: OS module has application in some basic operating system related utility functions.
syntex
var MyopSystem = require(“os”)

114. What is the property of OS module?
Answer:
Below is the property of OS module

os.EOL –This is a Constant for defining appropriate end of line marker for OS.

115. Explain Path module in Node.JS?
Answer: Path module are used for transforming and handling file paths using following syntex.
var mypath = require(“path”)

116. Explain Net module in Node.JS?
Answer: Net module can create both clients and servers and provide asynchronous network wrapper.
Syntex
var mynet = require(“net”)

117. NodeJS is client side server side language?
Answer:
NodeJS is a runtime system to create server-side applications.

118. What is Stub?
Answer: Stub is a small program to substitutes a longer program, possibly to be loaded later and that is located remotely. Stubs are programs which simulate the behaviour of modules.

119. What are Node.JS versions available?
Answer: Below are the NodsJS versions supported in operating systems –

OperatingSystem Node.js version
Windows node-v0.12.0-x64.msi
Linux node-v0.12.0-linux-x86.tar.gz
Mac node-v0.12.0-darwin-x86.tar.gz
SunOS node-v0.12.0-sunos-x86.tar.gz

120. How we can convert Buffer to JSON?
Answer: buffer.toJSON() is the syntex to convert Buffer to JSON.

121. How to concatenate buffers in NodeJS?
syntax
Answer: var MyConctBuffer = Buffer.concat([myBuffer1, myBuffer2]);

122. How to compare buffers in NodeJS?
Answer:Syntex
Mybuffer1.compare(Mybuffer2);

123. How to copy buffers in NodeJS?
Answer:Syntex

buffer.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])

124. What are the differences between readUIntBE and writeIntBE in Node.JS?
Answer: readUIntBE – It is a generalised version of all numeric read methods, it can support up to 48 bits accuracy. Set noAssert to “true” to skip the validation.

writeIntBE – It will write the value to the buffer at the specified byteLength and offset and it can  support upto 48 bits of accuracy.

125. Why to use __filename in Node.JS?
Answer: _filename is  the filename of the code which is being executed and it helps to resolve the absolute path of file.
Syntex

Console.log(__filename);

126. Why to use ClearTimeout in Node.JS?
Answer: This is the global function which is used to stop a timer which was created during “settimeout()”.

127. Why to use Net.socket in Node.JS?
Answer: net.Socket is an abstraction of a local socket or TCP in node.js and it’s  instances implement a duplex Stream interface which can be created by the user and used as a client (with connect() function) or it can be created by Node and can be passed to the user through the ‘connection’ event of a server.

128. Which events are emitted by Net.socket?
Answer: List of events emitted by Net.socket –

1.Connect

2.Lookup

3.End

4.Data

5.Close

6.Drain

7.Timeout

8.Error

129. What are the binding in domain module in Node.JS?
Answer: There are two bindings

1 .External Binding and

2.Internal Binding

130. Explain RESTful Web Service?
Answer: Web services which uses REST architecture are known as RESTful Web Services. It uses HTTP protocol and HTTP methods.

131. How to truncate the file in Node.JS?
Answer: Syntex to truncate the file       
fs.ftruncate(fd, len, callback)

132. Commands to work with the file from the local database.
Answer: Following are the commands to work with the file from the local database

Var fs = require(‘fs’);

Read: fs.readFile();

Create:

  • appendFile();
  • open();
  • writeFile();

Write: fs. writeFile();

Delete: fs.unlink();

Rename: fs.rename();

Update:

  • appendFile()
  • writeFile()

133. What kind of applications can be built by Node.JS?
Answer: DIRT, JSON, I/O Bound, Single Page applications can be built by Node.JS.

134. What is cluster?
Answer: Cluster is a process for handling thread execution load while working with multi-core systems.

135. How does URL module works?
Answer: URL module can help URL to parse it into host, pathname, search, query, etc.

Example:

var url = require(‘url’);

var adr = ‘https://mindmajix.com/?s=node+js+training’;

var q = url.parse(adr, true);

console.log(q.host); //returns ‘mindmajix.com’

console.log(q.search); //returns ‘?s=node+js+training’

 

136. Explain use of nodemailer module.

Answer: It is not the part of default modules list, but it has to be installed using npm.

Var nodemailer = require(‘nodemailer’);

137. What are the types of versions available?
Answer: Below are the types of versions available
1.Patch_Version,
2.Minor_Version,
3.Major_Version.

138. Node JS Vs Ruby.
Answer: Node js is an Event driven networking system written in c, c++ and javascript Ruby is Web application framework written in ruby. Node ja is easy to implement and popular for its feature and ruby is complex to install and yet to be popular.

139. What is difference between LTS and Stable version of Node.js?
Answer:
Long Term Support version has at least 18 months support and maintenance, therefore it is more stable and secure and Stable version has 8 months support and maintenance.

140. Name some of the events fired by streams.
Answer: Following are the mostly used eventS fired by streams

data – If there is data available to read.

end – If there is no more data to read.

error – If there is any error receiving or writing data.

finish -If  all data has been flushed to underlying system

141. How to open a file using Node?
Answer: syntax to open a file in asynchronous mode:

fs.open(path, flags[, mode], callback)

142. Explain the difference between const and let in node js?
Answer:’let’ can be reassigned, but it cannot be redeclared in the same scope.
It is good to have for the vast majority of the code and It can significantly enhance  code readability and decrease the chance of a programming error.

’const’ can be assigned an initial value, but cannot be redeclared in the same scope, and cannot be reassigned. It is a good for both maintainability, readability and avoids using magic literals

143. How to know a user’s IP address in node js?
Answer: We can  use req.connection.remoteAddress to a get user’s IP address in node js.

144. How can we write a file in Node JS?
Answer: Syntax
fs.writeFile(filename, data[, options], callback)

145. How can we read a file in Node JS?
Answer: Syntax
fs.read(fd, buffer, offset, length, position, callback)

146. How can we close a file in Node JS?
Answer: Syntax
fs.close(fd, callback)

147. Why we have to keep separate Express app and server?
Answer: Express app encapsulates  API logical, which is  data abstraction where we should keep up DB logic or data models.

The server are differently handled as its sole responsibility is to keep the app/website running.

148. How can we delete a file in Node JS?
Answer: Syntax
fs.unlink(path, callback)

149. What is V8 Engine in Node JS?
Answer: V8 Engine is Google’s open source javascript and written in C++ and used inside Google Chrome. It was designed for increasing the performance of JavaScript execution inside web browsers.

150. How to connect MySQL database using node js?
Answer: To connect MySQL database using Node Js, below syntex can be used.
npm install mysql.

151. What are system configration needed to install Node JS?
Answer: System configuration which is needed to install nodejs are given below-
64-bit architecture
Kernel version 3.10 or higher
One of the following
Linux flavors
Ubuntu 14.04 / 15.10

CentOS 6.x

Red Hat Enterprise Linux (RHEL) 7.x

Debian 7.7

4 or more CPUs/cores

At least 16 GB of memory/RAM
At least 25 GB of disk space
Ports opened for inbound TCP traffic:
8800 (admin console)

8080 (registry)
8081 (website)

152. How to catch all uncaughtException for Node.js?
Answer: Use process ‘uncaughtException’ and ‘unhandledRejection’ event
Code Source
process

.on(‘unhandledRejection’, (reason, p) => {

console.error(reason, ‘Unhandled Rejection at Promise’, p);

})

.on(‘uncaughtException’, err => {

console.error(err, ‘Uncaught Exception thrown’);
process.exit(1);

});

153.  What are the types of modules in node.js
Answer: Modules are set of functionality or javascript libraries encapsulated into a single unit, that are reused throughout the Node.js application.
Following are the types modules

  1. Core Modules:

Node.js Core Modules are come with its Installation by default. It can be used  as per application requirements.

  1. Local Modules:

It is user defined modules that are used for specific projects and locally available in separate files or folders within project folders.

  1. 3rd Party Modules:

It can be downloaded using NPM (Node Package Manager).

154.  What are the difference between package.json and package-lock.json?
Answer: The package.json is used for defining project properties, description, author & license info etc.

The package-lock.json is used to lock dependencies to a specific version number.

155. Provide some example of config file separation for dev and prod environments.
Answer: A configuration setup should ensure:

  • keys should be read from file AND from environment variable
  • secrets should be kept outside committed code
  • config is hierarchical to find easily

Consider the following config file

var config = {

production: {

mongo : {

billing: ‘****’

}

},

default: {

mongo : {

billing: ‘****’

}

}

}

 

exports.get = function get(env) {

return config[env] || config.default;

}

It’s usage are

const config = require(‘./config/config.js’).get(process.env.NODE_ENV);

const dbconn = mongoose.createConnection(config.mongo.billing);

156. Write the code sample again without try/catch block.
Answer: Consider the code:

async function check(req, res) {

try {

const a = await someOtherFunction();

const b = await somethingElseFunction();

res.send(“result”)

} catch (error) {

res.send(error.stack);

}

}

Code without try/catch

async function getData(){

const a = await someFunction().catch((error)=>console.log(error));

const b = await someOtherFunction().catch((error)=>console.log(error));

if (a && b) console.log(“some result”)

}

157. Why Zlib is used in Node js ?
Answer: Zlib is Cross-platform data compression library which was written by Jean-loup Gailly and Mark Adler. In Node js, Threadpool, HTTP requests, and responses compression and Memory Usage Tuning can be zlibed by  installing node-zlib package.

158.  What are the two arguments that async.queue takes?
Answer: The two arguments are
1)      Task function
2)      Concurrency value

159. Explain the concept of URL module.
Answer: The URL module of Node.js can provide various utilities for URL resolution and parsing which helps in splitting up the web address into a readable format: Var url= require (‘url’);

160. What are some attributes of package.json?
Answer: These are some attributes of package.json
1.name − name of the package
2.version − version of the package
3.description − description of the package
4.homepage − homepage of the package
5.author − author of the package
6.contributors − name of the contributors to the package
7.dependencies − npm automatically installs all the dependencies node_module folder of the package.
8.repository −  url of the package and repository
9.main − entry point of the package
10.keywords − keywords

161. Write some of the flags used in read/write operation on files.
Answer: Following are some flags for read/write operations :
r − To read a file. An exception will occur if the file does not exist.
r+ − To read or write a file. An exception will occur if the file does not exist.
rs − To read a file in synchronous mode
rs+ − To read or write a file in synchronous mode
w − To Write a file.  If file does not exit, it is created. If file exists, then it is truncated.
wx − similar to ‘w’ but fails if path exists.

w+ − Open file for reading and writing. If file does not exit, it is created. If file exists, then it is truncated.

wx+ − similar to ‘w+’ but fails if path exists.

a − To append a file.  file does not exist,it is created.
ax − same as ‘a’ but fails if path exists.

a+ − To read and append a file.  file does not exist,it is created.

ax+’ − same as ‘a+’ but fails if path exists.

162. What is JIT and how is it related to Node JS ?
Answer: A JIT ( Just In Time) compiler is a program that can be used to send bytecode (it consists of instruction that can be interpreted) to the processor by converting it into instruction. Virtual machine of Nodejs has JIT compilation which can improve the execution speed of the code. The virtual machine can take the source code and converts to machine code in runtime.

163. How to create a simple server in Node js which returns Hello ?
Answer: Following are line of code, which can create a server in Node Js.

var http =require(‘http’);

http.createServer(function(req,res){

res.writeHead(200,{‘Content-Type’:’text/plain’});

res.end(‘Hello \n’);

}).listen(1320,’127.0.0.3′);

164.  what is Closures?
Answer: A Closure function can be defined within another scope which has access to all the variables within the outer scope.

165. How to use aggregation in Mongoose?
Answer: Aggregations are a set of functions which are used for manipulating the data that has been returned from a MongoDB query. Aggregations work as a pipeline in  Mongoose.
Syntex
db.customers.aggregate([ … aggregation steps go here …]);

166. List types of Http requests?
Answer: Http can define a set of request to perform the desired actions. These are
1.GET: Used to retrieve the data method and asked for the representation of the specifies resource.
2.POST: POST method is utilized for presenting an element to the predetermined resource, generally causing a change in state or reactions on the server.
3.HEAD: HEAD method is same as GET method but asks for the response without the response body.
4. PUT: PUT is used for substituting all current representations with the payload.
5.DELETE: DELETE is used for deleting the predetermined resource.
6.CONNECT: CONNECT request is used for settling the TCP/IP tunnel to the server by the target resource
7.OPTION: OPTION method is used for giving back the HTTP strategies to communicate with the target resource.
8.TRACE: TRACE method can echo the message which tells the customer how much progressions have been made by an intermediate server.
9.PATCH: PATCH method can give partial modifications to a resource.

167. What is the revealing module pattern?
Answer: Revealing module pattern ExposEs only the properties and methods we want via an returned Object.

var greeting = ‘Hello world’

function greet() {

console.log(greeting)

}

module.exports = {

greet: greet

}

168. What are CommonJs Modules ?
Answer: CommonJS Modules specifies an ecosystem for JavaScript outside on the server or for native desktop applications.

169. What are some new features introduced in ES6?
Answer: List of few new Features introduced in ES6

  1. const and let keywords
  2. Array helper functions such as map, filter, find, every, some, reduce
  3. Arrow functions
  4. Classes and enhanced object literals
  5. Template strings
  6. Default function arguments
  7. Rest and spread operators
  8. Promises
  9. Modules
  10. Multi-line Strings
  11. Destructuring Assignment

170. Write a simple code to enable CORS in Node js?
Answer: CORS (Cross-Origin Resource Sharing) is a mechanism which uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission for accessing selected resources from a server.

code to enable CORS on NodeJS

app.use(function(req, res, next) {

res.header(“Access-Control-Allow-Origin”, “*”);

res.header(“Access-Control-Allow-Headers”, “Origin, X-Requested-With, Content-Type, Accept”);

next();

});

171. How to generate unique UUIDs/ guid in Node Js?
Answer: Code demonstrates how to generate unique UUIDs/ guid in Node Js.

var uuid = require(‘node-uuid’);

// Generate a v1 (time-based) id

uuid.v1();

// Generate a v4 (random) id

uuid.v4();

172. What is CLI.
Answer: CLI (Command Line Interface) is a utility or program on your computer where users type commands to perform some action or run some script rather than clicking on the screen.

Following are some types of command line interfaces depending on which operating system are used
1.Bash on following  Linux.

2.Terminal of Mac.

3.Command Prompt or Powershell on Windows

4.Shell/ Command line/terminal on Unix and Ubuntu

173. Explain an error-first callback?
Answer: Error-first callbacks are used to pass both errors and data. Error has to be passed as the first parameter, and it has to be checked to see if something went wrong. Data are passed by additional  arguments.

fs.readFile(filePath, function(err, data) {

if (err) {

// handle the error, the return is important

// so execution stops here

return console.log(err)

}

// use the data object

console.log(data)

})

Node JS is a very popular open source cross platform run time environment to execute Javscript code outside of the browser. Node JS is one the most preferred platform to build APIs. As the modern architectures demand micro services and also APIs to be consumed by multiple applications, Node JS will only continue to be on high demand in future. Our hand picked 173 frequently asked Node JS interview questions given above will give excellent advantage to succeed in your next job interview.

Share this: