Top 30 Node JS Interview Questions & Answers

Node.js Interview Questions & Answers

 

  1. Why use Node.js?
    Node.js makes building scalable network programs easy. Some of its advantages include:
     It offers a unified programming language and data type
     Everything is asynchronous
     It yields great concurrency
     It is generally fast
     It almost never blocks

  2. Why is Node.js Single-threaded?
     Node.js is single-threaded for async processing. By doing async processing on a singlethread under typical web loads, more performance and scalability can be achieved as
    opposed to the typical thread-based implementation.

  3. What are the functionalities of NPM in Node.js?
    NPM (Node package Manager) provides two functionalities:
     Command line utility for installing packages, version management and dependency
    management of Node.js packages
     Online repository for Node.js packages

  4. What is the difference between Node.js and Ajax?
     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.
     Node.js and Ajax (Asynchronous JavaScript and XML) are the advanced
    implementation of JavaScript. They all serve completely different purposes.

  5. What are “streams” in Node.js? Explain the different types of streams present
    in Node.js.
    Streams are objects that allow reading of data from the source and writing of data to
    the destination as a continuous process.
    There are four types of streams.
     to facilitate both read and write operations
     is a form of Duplex stream that performs computations based on the available input
     to facilitate the reading operation
     to facilitate the writing operation

  6. What are exit codes in Node.js? List some exit codes.
    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:
     Internal Exception handler Run-Time Failure
     Internal JavaScript Evaluation Failure
     Unused
     Uncaught Fatal Exception
     Fatal Error
     Non-function Internal Exception Handler

  7. What are Globals in Node.js?
    Three keywords in Node.js constitute as Globals. These are:
     Buffer – it is a class in Node.js to handle binary data.
     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.

  8. How can you avoid callback hells?
    There are lots of ways to solve the issue of callback hells:
     modularization: break callbacks into independent functions
     use a control flow library, like async
     use generators with Promises
     use async/await

  9. What’s wrong with the code snippet?
    new promise((resolve,reject) => {
    throw new Error(‘error’)
    then(console.log)
    The Solution
    As there is no catch after then. This way the error will be a silent one; there will be no
    indication of an error thrown. To fix it, you can do the following:
    new promise((resolve,reject) => {
    throw new Error(‘error’)
    then(console.log).catch(console.error)

  10. What’s output of the following code snippet?
    Answer: 2

  11. Explain flow of the above code snippet
     A new Promise is created, that will resolve to 1.
     The resolved value is incremented with 1 (so it is 2 now), and returned instantly.
     The resolved value is discarded, and an error is thrown.
     The error is discarded, and a new value (1) is returned.
     The execution did not stop after the catch, but before the exception was handled, it
    continued, and a new, incremented value (2) is returned.
     The value is printed to the standard output.
     This line won’t run, as there was no exception.

  12. What are perfect areas to use Node.js?
     JSON APIs based Applications
     Single Page Applications
     I/O bound Applications
     Data Streaming Applications
     Data Intensive Real-time Applications (DIRT)

  13. What Are The Key Features Of Node.Js?
     There is an Active and vibrant community for the Node.js framework
     No Buffering
     Asynchronous event driven IO helps concurrent request handling
     Fast in Code execution
     Single Threaded but Highly Scalable
     Node.js library uses JavaScript
    Promise.resolve(1)
    .then((x) => x +1)
    .then((x) => { throw new Error(‘My Error’) })
    .catch(() => 1)
    .then ((x) => x +1 )
    . then ((x) => console.log(x))
    . catch(console.error)

  14. When To Not Use Node.Js?
    We should not use it for cases where the application requires long processing time. If the
    server is doing some calculation, it won’t be able to process any other requests. Hence,
    Node.js is best when processing needs less dedicated CPU time.

  15. List of most commonly used IDEs for developing node.js applications.
     Cloud9.
     JetBrains WebStorm.
     JetBrains InteliJ IDEA.
     Komodo IDE.
     Eclipse.
     Atom.

  16. How to Get Post Data in Node.Js?

  17. How to Make Post Request in Node.Js?

  18. How to create Http server In Node.Js?
    app.use(express.bodyParser());
    app.post(‘/’,function(request,response){
    console.log(request.body.user);
    });
    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)
    }
    }
    var http = require(‘http’);
    var requestListener = function(request,response) {

  19. What Is The Difference Between Nodejs, AJAX, And JQuery?
    Node.Js
    It is a server-side platform for developing client-server applications.
    AJAX (Asynchronous Javascript and XML)
    It is a client-side scripting technique, primarily designed for rendering the contents of a
    page without refreshing it.
    JQuery
    It is a famous JavaScript module with complements AJAX, DOM traversal, looping and so on.
    This library provides many useful functions to help in JavaScript development.

  20. How many types of Streams are present in Node.js?
     <Readable> – This is the Stream to be used for reading operation.
     <Writable> – It facilitates the write operation.
     <Duplex> – This Stream can be used for both the read and write operations.
     <Transform> – It is a form of a duplex Stream, which performs the computations based on
    the available input.

  21. What Is Package.Json?
     It is a plain JSON (JavaScript Object Notation) text file which contains all metadata
    information about Node.js Project or application.
     NPM (Node Package Manager) uses <package.json> file. It includes details of the Node.js
    application or package. This file contains a no. of different directives or elements. These
    directives guide NPM, about how to handle a module or package.
    response.writeHead(200, {‘Content-Type’:’text/plain’});
    response.end(‘Welcome’);
    }
    Var server = http.createServer(requestListener);
    server.listen(8080);

22.Name some of the attributes of package.json?
Following are the attributes of Package.json
name– name of the package
version– version of the package
description– description of the package
homepage– homepage of the package
author– author of the package
contributors– name of the contributors to the package
dependencies– list of dependencies. npm automatically installs all the dependencies mentioned
here in the node_module folder of the package.
brepository– repository type and url of the package
main– entry point of the package
keywords– keywords

  1. File IO operations
    Open a file using Node
    fs.open(path, flags[, mode], callback)
    Parameters
    Here is the description of the parameters used:
  2. path– This is string having file name including path.
  3. flags– Flag tell the behavior of the file to be opened. All possible values have been mentioned
    below.
  4. mode– This sets the file mode (permission and sticky bits), but only if the file was created. It
    defaults to 0666, readable and writeable.
  5. callback– This is the callback function which gets two arguments (err, fd).
    Read a file using Node
    fs.read(fd, buffer, offset, length, position, callback)
    This method will use file descriptor to read the file, if you want to read file using file name directly then you should use another method available.
    Parameters
    Here is the description of the parameters used:
  6. fd– This is the file descriptor returned by file fs.open() method.
  7. buffer– This is the buffer that the data will be written to.
  8. offset– This is the offset in the buffer to start writing at.
  9. length– This is an integer specifying the number of bytes to read.
  10. position– This is an integer specifying where to begin reading from in the file. If position is null, data will be
    read from the current file position.
  11. callback– This is the callback function which gets the three arguments, (err, bytesRead, buffer).

Write a file using Node
fs.writeFile(filename, data[, options], callback)
This method will over-write the file if file already exists. If you want to write into an existing file then you
should use another method available.
Parameters
Here is the description of the parameters used:
1. path– This is string having file name including path.
2. data– This is the String or Buffer to be written into the file.
3. options– The third parameter is an object which will hold {encoding, mode, flag}. By default encoding is
utf8, mode is octal value 0666 and flag is ‘w’
4. callback– This is the callback function which gets a single parameter err and used to return error in case of
any writing error.
How will you close a file using Node?
Following is the syntax of one of the methods to close an opened file:
fs.close(fd, callback)
Parameters
Here is the description of the parameters used:
1. fd– This is the file descriptor returned by file fs.open() method.
2. callback– This is the callback function which gets no arguments other than a possible exception are given to
the completion callback.
How will you delete a file using Node?
Following is the syntax of the method to delete a file:
fs.unlink(path, callback)
Parameters
Here is the description of the parameters used:
1. path– This is the file name including path.
2. callback– This is the callback function which gets no arguments other than a possible exception are given to
the completion callback.

  1. How to handle the “Unhandled exceptions” in Node.js?
    It can be caught at the “Process level” by attaching a handler for uncaughtException event.
    Example:
    Process.on (‘uncaught Exception’, function (err) {
    Console.log(‘Caught exception: ‘ + err);
    });

  2. How to build a “Hello World” Application in Node.js?
     Create a folder called ‘hello_world’.
     Initialize the project with command ‘npm init’, this will create the package.json.
     The project name only support URL friendly character and no longer support Capital
    letters.
     This command will create the package.json.
    A. Install all dependencies using the command ‘npm install’.
    B. Start the project by running the command ‘node’.
    C. This will provide the option to write other things.
    D. Let’s print ‘Hello World!’.
    E. Every JavaScript function must return something, this console.log return undefined ,
    therefore , the second line prints ‘undefined’.
    F. Create a file called ‘index.js’ inside ‘hello_world’ folder.
    From command line tool run ‘node index.js’.

  3. Where to deploy node application?
     Node.js app cannot be deployed on existing hosts like shared web hosting etc.
     Use VPS or dedicated servers to install node and run your application.
     The easiest way to deploy node application is to use a scalable service like Heroku, which
    is completely free and you only need to pay when you are using more resources.

  4. Explain Node.js Code Execution Process?
    The steps of code execution are given below:
     Clients send theirs request to Node.js Server.
     Node.js Server receives those requests and places them into a processing Queue that is
    known as “Event Queue”.
     Node.js uses JavaScript Event Loop to process each client request. This Event loop is an
    indefinite loop to receive requests and process them. Event Loop continuously checks for
    client’s requests placed in Event Queue. If requests are available, then it process them
    one by one.
     If the client request does not require any blocking IO operations, then it process
    everything, prepare the response and send it back to the client.
     If the client request requires some blocking IO operations like interacting with database,
    file system, external services then it uses C++ thread pool to process these operations.

  5. What are core modules in Node.js?
    Assert It is used by Node.js for testing itself. Usage – require(‘assert’).
    Buffer It is used to perform operations on raw bytes of data which reside in
    memory. Usage – require(‘buffer’).
    Child Process It is used by node.js for managing child processes. It can be accessed with It
    Usage – require(‘child_process’).
    Cluster This module is used by Node.js to take advantage of multi-core systems, so
    that it can handle more load. Usage -require(‘cluster’).
    Console It is used to write data to console. Node.js has a Console object which
    contains functions to write data to console. Usage -require(‘console’).
    Crypto It is used to support cryptography for encryption and decryption. Usage –
    require(‘crypto’).
    Debugger It is used for code debugging. To use this, start Node.js with the debug
    argument and for debugging add debugger; statement in your code.
    DNS It is used to perform operations like lookup and resolve on domain names.
    Usage – require(‘dns’).
    Events It is used for events handling in node.js. In node.js, events are emitted by
    other node objects. Usage – require(‘events’).
    File System It is used to perform operations on files. Usage – require(‘fs’).
    HTTP It is used to create Http server and Http client. Usage – require(‘http’).
    Net It used to create TCP server and client which can communicate over a
    network using TCP protocol. Usage – require(‘net’).
    OS It is used to provide basic operating system related utility functions. Usage –
    require(‘os’).
    Path It is used to perform operations on paths of files. Usage – require(‘path’).
    Process It is a global object and provides information related to the program
    execution. Usage – require() method.
    Query String It is used to deal with query strings.
    Stream It is used to stream data between two entities. Usage – require(‘stream’).
    Timers All of the timer functions are global and deals with time. Usage – require()
    method.
    Url It is used for URL resolution and parsing. Usage – require(‘url’).
    Util It is primarily designed to support the needs of Node.js internal APIs. It is
    also useful for debugging. Usage – require(‘util’).

  6. What are various error handling patterns in Node.js?
    There are following basic patterns you can use for errors handling in Node.js:
    • Try/Catch – The most commonly used way to handle errors in any programming language
    is try/catch blocks. Also, try/catch block executes in synchronous fashion; hence suitable
    for compiled languages like C#, Java etc.
    try {
    throw new Error(‘throw error’);
    } catch (e) {
    console.log(e);
    }
    Node.js to handle errors for synchronous code.
    • Callback – This way is used to handle errors in any callback without using nested try
    catch statements. In this way you have to pass a callback, function(err, result) which will
    be invoked when the asynchronous operation completes. Here err parameter returns the
    error and result is the result of completed operations, depending on whether the
    operation succeeded or failed.
    //request in express
    app.get(‘/’, function (req, res) {
    db.query(‘sql_query’, function (err, result) {
    if (err) {
    res.writeHead(500);
    res.end();
    console.log(err);
    }
    else {
    res.send(result);
    }
    });
    });

  7. What are various node.js web development frameworks?
    The best and most powerful node.js web development frameworks to build real time and
    scalable web applications with ease are given below:
    MVC frameworks
    • Express
    • Koa
    • Hapi
    • Sails
    • Nodal

  8. What are various node.js testing frameworks?
    The most popular node.js testing libraries and frameworks are given below:
    • Node.js assert
    • Mocha
    • Chai.js
    • Should.js
    • Nodeunit
    • Vows.js
    • Jasmine

%d bloggers like this: