NODE.JS INTERVIEW QUESTIONS ANSWERS

Node Js is one of the most popular and powerful server technologies today.
It allows you built the entire website only in one programming Language i.e Javascript. Node js is free and open source server technology that uses Javascript to create complete web software.It runs on various platforms like Windows, Linux, Unix, Mac OS X, etc.

CLI stands for Command Line Interface. It 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.
There are different types of command line interfaces depending on which operating system you are using. We have listed some of them below.

  • Bash on Linux.
  • Terminal of Mac.
  • Command Prompt or Powershell on Windows
  • Shell/ Command line/terminal on Unix and Ubuntu

Node.js makes building scalable network programs easy. Some of its advantages include:

  • It is generally fast
  • It almost never blocks
  • It offers a unified programming language and data type
  • Everything is asynchronous 
  • It yields great concurrency

Node.js is a single-threaded but highly scalable system that utilizes JavaScript as its scripting language. It uses asynchronous, event-driven I/O instead of separate processes or threads. It is able to achieve high output via single-threaded event loop and non-blocking I/O.

console.log(“first”);
setTimeout(function() {
    console.log(“second”);
}, 0);
console.log(“third”);

Output:

first
third
second

In Node.js version 0.10 or higher, setImmediate(fn) will be used in place of setTimeout(fn,0) since it is faster. As such, the code can be written as follows:

console.log(“first”);
setImmediate(function(){
    console.log(“second”);
});
console.log(“third”);

Node js is written in C, C++,JavaScript.It uses Google’s open source V8 Javascript Engine to convert Javascript code to C++.

Use node -v command to check the installed version of Node Js.

Modules are reusable block of code whose existence does not impact other code in any way. It is not supported by Javascript. Modules are introduced in ES6. Modules are important for Maintainability, Reusability, and Namespacing of Code.

You use the following 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

Node.js can be used for the following purposes

a)      Web applications ( especially real-time web apps )

Network applications

c)       Distributed systems

d)      General purpose applications

The two types of API functions in Node.js are

a)      Asynchronous, non-blocking functions

b)      Synchronous, blocking functions

For async processing, Node.js was created explicitly as an experiment. It is believed that more performance and scalability can be achieved by doing async processing on a single thread under typical web loads than the typical thread based implementation.

A callback function is called at the completion of a given task. This allows other code to be run in the meantime and prevents any blocking.  Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks. 

Callback hell is the result of heavily nested callbacks that make the code not only unreadable but also difficult to maintain. For example:

query(“SELECT clientId FROM clients WHERE clientName=’picanteverde’;”, function(id){
  query(“SELECT * FROM transactions WHERE clientId=” + id, function(transactions){
    transactions.each(function(transac){
      query(“UPDATE transactions SET value = ” + (transac.value*0.1) + ” WHERE id=” + transac.id, function(error){
        if(!error){
          console.log(“success!!”);
        }else{
          console.log(“error”);
        }
      });

});

  });
});

require() is used to include modules from external files in Node Js. It is the easiest way to include a module in Node. Basically require is a function that takes a string parameter which contains the location of the file that you want to include. It reads the entire javascript file, executes the file, and then proceeds to return the exports object.
Syntax:

require('path');

No, you cannot access DOM in node.

Node.js is quickly gaining attention as it is a loop based server for JavaScript. Node.js gives user the ability to write the JavaScript on the server, which has access to things like HTTP stack, file I/O, TCP and databases.

To process and handle external events and to convert them into callback invocations an event loop is used. So, at I/O calls, node.js can switch from one request to another

By following steps you can async Node.js

a)      First class functions

b)      Function composition

c)       Callback Counters

d)      Event loops

As the name suggests, REPL (Read Eval print Loop) performs the tasks of – Read, Evaluate, Print and Loop. The REPL in Node.js is used to execute ad-hoc Javascript statements. The REPL shell allows entry to javascript directly into a shell prompt and evaluates the results. For the purpose of testing, debugging, or experimenting, REPL is very critical.

Node.js and Ajax (Asynchronous JavaScript and XML) are the advanced implementation of JavaScript. They all serve completely different purposes.  

Ajax is primarily designed for dynamically updating a particular section of a page’s content, without having to update the entire page. 

Node.js is used for developing client-server applications.

Chaining is a mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations.

The basic purpose of using alternative texts is to define what the image is about. During an image mapping, it can be confusing and difficult to understand what hotspots correspond to a particular link. These alternative texts come in action here and put a description at each link which makes it easy for users to understand the hotspot links easily.

Pros:

a)      If your application does not have any CPU intensive computation, you can build it in Javascript top to bottom, even down to the database level if you use JSON storage object DB like MongoDB.

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

Cons:

a)       Any intensive CPU computation will block node.js responsiveness, so a threaded platform is a better approach.
b)      Using relational database with Node.js is considered less favourable

In node.js “non-blocking” means that its IO is non-blocking.  Node uses “libuv” to handle its IO in a platform-agnostic way. On windows, it uses completion ports for unix it uses epoll or kqueue etc. So, it makes a non-blocking request and upon a request, it queues it within the event loop which call the JavaScript ‘callback’ on the main JavaScript thread.

Exit codes are specific codes that are used to end a “process” (a global object used to represent a node process). 

Examples of exit codes include:

  • Unused
  • Uncaught Fatal Exception
  • Fatal Error
  • Non-function Internal Exception Handler
  • Internal Exception handler Run-Time Failure
  • Internal JavaScript Evaluation Failure

By writing following line of code, you 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 World\n');

}).listen(1320,'127.0.0.3');

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

Three keywords in Node.js constitute as Globals. These are:

  • Global – it represents the Global namespace object and acts as a container for all other objects.
  • Process – It is one of the global objects but can turn a synchronous function into an async callback. It can be accessed from anywhere in the code and it primarily gives back information about the application or the environment. 
  • Buffer – it is a class in Node.js to handle binary data. 

Angular.JS is a web application development framework while Node.js is a runtime system. 

Following is the syntax of the method to open a file in asynchronous mode:

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

Parameters

Here is the description of the parameters used:

  • path − This is string having file name including path.

  • flags − Flag tells the behavior of the file to be opened. All possible values have been mentioned below.

  • mode − This sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.

  • callback − This is the callback function which gets two arguments (err, fd).

Using Node Js you can build applications like:

  • Internet of Things
  • Real-Time Chats Applications
  • Complex Single-Page Applications
  • Real-Time Collaboration Tools
  • Streaming apps
  • Microservices / API’s

The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.

This function returns an opaque value that represents the timer which can be used to clear the timer.

Leave a Reply