Loading…
Node js Interview Questions

An Overview of Node js

Node js, as 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 Nodejs 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.

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 11.14.0, released on October 2018
Created By Ryan Dahl
Written in C, C++, JavaScript
Official Website https://nodejs.org/en/

Development History of Node JS

Ryan Dahl conceived the idea of Node js in 2009.

Latest Version : The current version is v11, which was released in October 2018. Candidates report that this information was a part of Node js interview questions.

Advantages

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

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 js interview questions and answers. Though every interview is different, we can help you crack your next interview with the most commonly asked interview questions.

Node js Interview Questions and answers

Looking for a new job? Do not miss to read our Node js Interview Questions and answers. Whether you are a fresher or an experienced, these questions and answers that can help you to crack your interview.

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.

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.
  • 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.

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.

In order to avoid callbacks, use any one of the following routes:

  • Use modularization as it will break callback into an independent function.
  • Use promises.
  • Use yield with Promises and Generators.
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

Both Node.js and jQuery are the advanced implementation 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.

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

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.

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

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

  • HttpOnly
  • secure

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

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

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

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

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

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

There are two types of API in Node JS.

  • Blocking functions
  • Non-blocking functions

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.

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.

You can try the following command for uninstalling the module.

C:\Nodejs_WorkSpace>npm uninstall dependency-name

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

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

Syntax of close a file is given below :-

fs.close(fd, callback)

Syntax of delete a file is given below :-

fs.unlink(path, callback)

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.

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.

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.

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.

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.

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.

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.

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.

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

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.

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.

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.

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.
  • Facilitate writing operation.
  • Facilitate both reading and writing operations.
  • Kind of duplex stream that performs the computations based on the available inputs.

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.

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)

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

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.

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