Loading…

Node js Interview Questions

Last update: 30 Nov 2019, 71 Questions and Answers

A Quick Overview of Node js Interview Questions

Node js Interview Questions

Node.js is an open-source and cross-platform development framework that uses an event-driven, non-blocking I/O model. It is a freely available platform that can handle thousands of concurrent connections with minimal overhead. Node.js makes use of event-loops through JavaScript call back functionality to implement the non-blocking I/O. All the programs for Node.js are written in JavaScript and everything inside Node.js runs in a single thread. In the blog post, a number of node js interview questions are discussed which will helpful for the candidates to understand the fundamental and advanced level features of Node.js framework.

About Node js
What is Node js It is a free and open-source server environment. It runs on various platforms like Linux, Unix, Mac OS X, Windows, etc. It uses asynchronous programming.
Latest Version 13.1.0, released in 5th November 2019
Created By Ryan Dahl
Written in C, C++, JavaScript
Express Licence MIT License

Most Frequently Asked Node js Interview Questions And Answers With Examples:

Node.js, as open source server environment, runs on various platforms such as Windows, Unix, Linux, etc. The anchor of the MEAN stack, Node.js is also one of the most popular server platforms in the world.

Why it is used?
  • It is asynchronously programming, runs single-threaded, non-blocking which is very memory efficient.
  • It can operate file various operations like create, open, write, read, delete, and close files on the server and can collect form data.
5 1

The NPM provides two main functionalities:

  • It is the online repository for all of the Node.js packages.
  • It is the command line utility for installing, version management and dependency management of the Node.js packages.
3 0
  • Go to the Nodejs.org site and download the binary files and Windows installer.
  • Run the Windows installer.
  • Follow the instructions on the screen for accepting the license agreement, clicking the NEXT button a few times and allowing the default settings.
  • You will have to restart your computer. Remember that you may not be able to run Node.js until you restart your computer.
  • Make sure you have installed Node by running simple commands just to see what version got installed.

Note: You can visit our latest blog How to install node js

1 0

A callback function is done at the completion of a task. This function allows other codes to be run in the meanwhile and prevent blocking. Because Node.js is an asynchronous platform, it relies heavily on the callback function. In addition, the APIs also support callbacks.

Note: This is a fundamental node js interview questions.

0 0
  • Step1. Install Async first with "npm install async" command
  • Step2. Call the async in your file with you will use async.
    var async = require("async");
  • Step3. Make an async function and call await function inside async function.
    let phoneChecker = async function (req, res) {
         const result = await phoneExistOrNot();
    }
    exports.phoneChecker = phoneChecker;

    await will work only under async function.

    For example: here is " phoneChecker " is async function, and phoneExistOrNot is await service.
  • Step4. Now you can write your logic in await function.
    let phoneExistOrNot = async function (req, res){
        return new Promise(function(resolve, reject) {
            db.query('select name, phone from users where phone = 123456789 ', function (error, result) {
                 if(error) {
                     reject(error);
                     console.log('Error');
                 } else {
                      resolve(result);
                      console.log('Success');
                 }
          })
    });
    }

We have a separate blog for this topic. You can also read this concept in details
How to use async-await in node js

0 1
We can avoid callback hell by different available solutions, as mentioned below.

Promises: The promise is s result of an asynchronous operation. We can create a promise on these three states:

  • Pending: When the initial state is not fulfilled or rejected.
  • Fulfilled: When the operation gets completed successfully.
  • Rejected: When the operation gets failed.

Generators: These are functions which can be resumed and paused. It doesn’t get executed immediately when called. Instead, it returns a generator object or generator object with which we can control the execution of the function.

0 1
S.no let const
1. It can be reassigned, but can’t be redeclared in the same scope. It can be assigned an initial value, but can’t be redeclared in the same scope, and can’t be reassigned.
2. It is beneficial to have for the vast majority of the code. It can significantly enhance your code readability and decrease the chance of a programming error. It is a good practice for both maintainability, readability and avoids using magic literals
0 0

Both Node.js and jQuery are the advanced implementations of JavaScript. Node.js is a server-side platform for developing client-server applications. However, Node.js can also run on a server similar to Apache and Django, but not in a browser. jQuery is a JavaScript module that complements AJAX, looping, DOM traversal. It provides useful functions that help in JavaScript development. jQuery also manages cross-browser compatibility and can help produce extensive web applications.

Point to be noted: Go through this Q&A very thoroughly as this is one of the critical node js interview questions.

0 1

You can use req.connection.remoteAddress to a user's IP address in node js.

0 0

This is a mechanism by which the output of one stream is connected to the output of another stream y creating a long chain of multiple stream operations.

0 0

Node JS is used to develop server side applications but Angular JS is used to client side applications.

Node JS was developed by Ryan Dahl in 2009 but Angular JS developed by Misko hevery( Google developer ) in 2008 and 2009.

Both are open-source tools that is used to create isomorphic web applications

0 0

we have to set flags on the set-cookie HTTP header:

  • HttpOnly
  • secure

After this it will lokk like this : Set-Cookie: sid=; HttpOnly

Point to be noted: Make sure that you go through this twice as this is the favorite node js interview questions for fresher and experienced as well.

0 0

It is used to include modules from external files. It takes one string parameters( location of file ) that we want to include.

Example

                                                    

require('file location')

1 0

Example

                                                    

$ 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

0 1

It is a global class that can be accessed in an application without importing the buffer module. It can be constructed in a variety of ways like var buf = new Buffer(5);

1 0

A pipe is a function that reads the data from a readable stream once it is available and writes it in the destination writable stream. It performs all the reasonable things including the errors, files in case any one side falls apart. In due case, piping redirections any readable stream to a writable stream.

2 0

open() function is used to opens a file by passing a file name.

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

Parameters

  • path : It is a string having file name with complete path
  • flags : It indicates the behavior of the file to be opened
  • mode : It sets the file mode like permission
  • callback : gets two arguments (err, fd)

Example

                                                    
var fs = require("fs");

// Asynchronous - Open a File
console.log("open file");
fs.open('file.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
   console.log("File opened");     
});
1 0

setTimeout() : It can be used to schedule code execution after a designated amount of milliseconds.

function myFunc(arg) {
  console.log(`arg was => ${arg}`);
}

setTimeout(myFunc, 1500, 'funky');

clearTimeout()  :  It can be used to cancel timeout which are set by setTimeout().

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');

Note: This is very important node js interview question.

0 0

There are two types of API in Node JS.

  • Blocking functions
  • Non-blocking functions
0 0

The timing feature of node.js contains all the necessary functions that are required to execute code after any specific period. As it is built on the V8 JavaScript engine of Google Chrome, hence its library permits the fast execution of code. Timers also provide a number of ways for managing schedules. They don't need to be imported as all the methods are easily available for the browser.

Some modules are –
  • setTimeout
  • setInterval
  • setImmediate
  • clearImmediate(immediate)
  • clearTimeout(timeout)
1 0
Some tools and IDEs are -
  • Mocha.js
  • Chai
  • Sinon.js
  • Express.js
  • WebStorm IDE
  • Passport.js
  • Cloud9
  • IntelliJ IDEA
  • Sublime text
0 0

Error-first callbacks are generally used to pass errors as well as data. It is important to pass the error as the first parameter, and then you must check if something went wrong. There are additional arguments that are used to pass data.

0 0

Reactor Pattern is used for non-blocking Input/Output operations in the Node.js. This pattern provides a handler that is associated with I/O operations. When I/O requests are generated, they get submitted to a demultiplexer, which handles concurrency in non-blocking I/O mode and collects request in the form of an event and queues the events.

0 0

You can try the following command for uninstalling the module.

C:\Nodejs_WorkSpace>npm uninstall dependency-name

0 0
  • newListener
  • removeListener
  • EventEmitter: 'removeListener'
  • EventEmitter. listenerCount (emitter, eventName)
  • EventEmitter.defaultMaxListeners
  • emitter.addListener(eventName,listener)
  • emitter.emit(eventName[,...args])
0 0

Syntax of read a file is given below:-

fs.read(fd, buffer, offset, length, position, callback)

Example

                                                    var fs = require("fs");
var buf = new Buffer(1024);

console.log("open existing file");
fs.open('file.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
   console.log("File opened");
   console.log("read the file");
   
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }
      console.log(bytes + " bytes read");

      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});
                                                
0 0

Syntax of write a file is given below :-

fs.writeFile(filename, data[, options], callback)

Example

                                                    
var fs = require("fs"); console.log("Write in existing file"); fs.writeFile('file.txt', 'This is test msg', function(err) { if (err) { return console.error(err); } console.log("Written successfully!"); console.log("Read latest written data"); fs.readFile('file.txt', function (err, data) { if (err) { return console.error(err); } console.log("Read: " + data.toString()); }); });
0 0

Syntax of close a file is given below :-

fs.close(fd, callback)
0 0

Syntax of delete a file is given below :-

fs.unlink(path, callback)
0 0

A test pyramid is a metaphor that helps the grouping of software tests in a bunch of different granularity. Unit testing pyramid number of tests gets easily fitted.

For instance, unit testing, component testing, integration testing, system testing, end-to-end testing, UI testing, and others. The primary example of it is creating a unit test which will be the fastest and reliable.

0 0

Express app encapsulates your API logical, which is your data abstraction. This is where you should keep up your DB logic or data models.

The server should be differently handled as its sole responsibility is to keep the app/website running. The separation of concerns will lead to optimization.

0 0

setImmediate() executes a script once the current poll or the event loop phase has completed.

setTimeout() is used to schedule scripts to be run after a minimum threshold has elapsed.

The order in which these timers are executed varies on the context in which they are used. If both are called from within the module, timing will be bound by the process performance.

0 0

Node.js appeared when the engineers of JavaScript expanded it from something you could just keep running in the browser to something you could keep running on your machine as an independent application. The Node run-time environment incorporates all that you have to execute a program written in JavaScript.

0 0
Operational errors programmer errors
They are not a bug They are the actual bug
They are not a bug They are the actual bug
They can't corrupt can corrupt the whole system
It refers to know cases It refers to unknown cases
Example: you can consider request timeout for any hardware failure
0 0

Hapi.js or Express.js is robust and modular for developing the APIs. It has input validation, configuration functioning, and many other features.

0 0

Express js is a type of framework which is used for node js. It released under the MIT License. It helps to manage a server and routes. It is also designed for building web applications and APIs.

It was founded by TJ Holowaychuk. The first release of express js was on the 22nd of May, 2010. Version 0.12.0.

Features of Express framework:
  • It can be used to design single-page or multi-page web applications.
  • It helps to setup middlewares to respond to HTTP Requests.
  • It helps us to render HTML Pages dynamically.
0 0
  • Node.js lacks consistency, and its API changes frequently.
  • It requires more time for development, which affects productivity.
  • Users who prefer heavy computing applications cannot find it reliable
  • It is advanced, but there are a few poor qualities of tools present in it.
0 0

Yes, system configuration need to install nodejs that's 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)
  • Access to the public internet, either directly or via proxy

0 0

In Node.JS, module.exports is a special object that is included in every JavaScript file present in the Node.JS file default. Here module is a variable that represents the current module, and export is the object that will be exposed as the module.

0 0

The array of records can easily be bulk inserted into the node.js. Before insertion, you have to convert it into an array of arrays.

Example

                                                    

var mysql = require('node-mysql');
var conn = mysql.createConnection({
     // your database connection
});

var sql = "INSERT INTO Test (name, email) VALUES ?";
var values = [
    ['best interview question', 'info@bestinterviewquestion.com'],
    ['Admin', 'admin@bestinterviewquestion.com'],
];

conn.query(sql, [values], function(err) {
     if (err) throw err;
     conn.end();
});

0 0

If you don't install MySQL then you can install MySQL by npm install mysql.

Example

                                                    
Create Connection

You can write connection code in a single file and call in all pages where you need to interact with database.

var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "your database username",
password: "database password"
});

con.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});

 

0 0

Consistent style can help your team members modify projects easily without the need to learn a new style for every project. Some of the useful tools are Standard and ESLint.

0 0

The Long Term Support (LTS) version of Node.js receives all of the critical bug fixes, performance improvements, and security updates. The LTS versions are supported for at least 18 months and are always even version numbers. They are best for production because the LTS release line focuses on stability and security.

0 0

They have globally installed packages or dependencies that are stored in the /npm directory. These dependencies can be used in Command Line Interface (CLI) of any node.js. However, they cannot be imported using require () command in Node application directly. In order to install a Node project globally, you need to use -g flag.

0 0

Local mode is the package installation in the node-modules directory in the same folder where Node application is stored. By default, the Node Package Manager (NPM) installs dependencies in the local mode. Most locally deployed packages are also accessible via require(). In order to install a Node project locally, you need to follow the syntax.

0 0

EventEmitter class lies in the events module, and is accessibly through the following syntax:

//import events module
var events = require('events');
//create an eventEmitter object
var eventEmitter = new events.EventEmitter();

In case an EventEmitter instance is facing error, it emits 'error' event. When a new listener is added, the 'newListener' event gets fired and when a listener gets removed, 'removeListener' event gets fired.

0 0

Every method in the fs module contains synchronous as well as asynchronous form. Asynchronous methods take the last parameter as completion function callback and the first parameter as an error. It is advisable to use asynchronous methods instead of synchronous methods because asynchronous would never block the program execution, but synchronous may block.

0 0

V8 Engine is Google's open source javascript and written in C++. It is used inside Google Chrome. It was first designed to increase the performance of JavaScript execution inside web browsers.

0 0
  • Scalable and extensible
  • Easy to learn
  • Used as a Single Programming Language
  • Offers benefits of Fullstack JS
  • Offers High Performance
0 0

package.json is the most important file of any Node.js project and it contains the metadata of the project. It is used to give information to NPM that allows it to identify the project. It handles the project's all dependencies. It is placed on root of any project.

1 0

The Read Eval Print Loop (REPL) performs these four tasks - Read, Evaluate, Print and Loop. The REPL is used to execute ad-hoc Javascript functions. The REPL shell allows direct entry of javascript into a shell prompt and evaluates the results. REPL is very critical for testing, debugging, or experimenting.

0 0

Node.js and Asynchronous JavaScript and XML (Ajax) are the advanced implementations of JavaScript. Ajax is designed for dynamically updating a section of a page’s content, without having to update the entire web page. Node.js is utilized for developing client-server applications.

1 0

Streams are the objects that allow and enable the continuous process of reading the data from the source code and writing the data to the destination.

Streams are of four types:

  • Facilitate reading operation (Readable).
  • Facilitate writing operation (Writable).
  • Facilitate both reading and writing operations (Duplex).
  • Kind of duplex stream that performs the computations based on the available inputs (Transform).
0 0

Exit codes are the specific codes that can be used to end a process. Some of the examples of exit codes are, Uncaught Fatal Exception, Fatal Error, Non-function Internal Exception Handler, Internal Exception handler Run-Time Failure, Internal JavaScript Evaluation Failure, etc.

0 0

It is a returned value by an asynchronous function to indicate the completion of the processing carried out by the function.

Example

                                                    

var promise = doSomethingAync()

promise.then(onFulfilled, onRejected)

0 0

It is the process of creating fake endpoints in code so that we can delay writing complex code.

  • It is compatible with Node js
  • It comes with predefined or usable extensions
  • It is simple,lightweight
0 0

Node.js is single-threaded because of async processing. When you do async processing on a single-thread under web loads, better performance and more scalability can be achieved as compared to typical thread-based implementation.

0 0
It is a single-threaded application, but it can support the concept of event and callbacks.
0 0

Node js, an open-source server environment, runs on various platforms such as Windows, Unix, Linux, etc. That means if you have knowledge of Node.js, and if you have read our Node js interview questions, your job prospects are excellent. The anchor of the MEAN stack, Node.js is also one of the most popular server platforms in the world. In today's scenario, it has been analyzed that a number of companies namely LinkedIn, Microsoft, Netflix, SAP, PayPal, Walmart, etc.

Advantages of Node.js

  • Developers can create an HTTP server, DNS server, Static File server, Web chat Applications and many more.
  • It is quite easy to scale the Node.js applications in the vertical and horizontal direction
  • It is easier to learn and understand
  • Node.js is used as SPL (Single programming language)
  • It offers high performance and Fullstack JS

Disadvantages of Node.js

  • It does not support a strong library system
  • Offer not- stable Application Programming Interface
  • It adopts asynchronous programming model
  • Lack of standard libraries
  • It is not ideal for intensive and complex applications

Installation Steps

  • Go to the Nodejs.org site and download the binary files and Windows installer.
  • Run the Windows installer.
  • Follow the instructions on the screen for accepting the license agreement, clicking the NEXT button a few times and allowing the default settings.
  • You will have to restart your computer. Remember that you may not be able to run Node.js until you restart your computer.
  • Make sure you have installed Node by running simple commands just to see what version got installed.

 

We can help you prepare for the Node interview questions. Though every interview is different, we can help you crack your next interview with the most commonly asked interview questions.

Add Review

Ask Question