12Apr
Top 15 Node.js Interview Questions | Theory and Practice for 2019
The technical interview grind continues

Node.js, a JavaScript run-time environment used by countless remote professionals today, took the web development sphere by storm when it was first introduced 10 years ago, in 2009: no longer were web developers limited to sandboxed environments like Java — instead, they could finally capitalize on JavaScript’s potential to its fullest.

The best remote Node.js developer is a well-rounded professional who lives by a paraphrased Hippocrates saying: “Trends are short and knowledge is long”. In a pool of numerous Node.js interview questions, you can count on this article to guide you to ace your next technical interview!

Theory

Coding is surely important — just like understanding the underlying metrics and logic behind its performance. How can Node.js be used in the real world? What advantages does it offer? How does its non-blocking I/O model function? Let’s find out!

1. Where can Node.js be applied?

Generally, Node.js excels in apps that require a lot of disk/network access.

  • Real-time applications: as such apps require large amounts of input/output operations, Node.js is a perfect fit — its async nature manages to handle the load seamlessly. Typical examples are online services like Google Docs/Sheets and chat rooms.
  • Data streaming apps: Node.js manages to combine processing and downloading/uploading data simultaneously in an effective manner.
  • REST APIs: Node.js’ rich ecosystem includes the Express.js framework — this makes a killer combo for creating efficient and fast REST APIs.
  • Feature-rich Single Page Applications: Node’s event loop allows for seamless data update; furthermore, front-end frameworks like Angular, React, and Vue used for creating SPAs share its JavaScript nature with Node.js, allowing for easier development via reusable structures and components.

(Conversely, a service that requires heavy CPU usage (e.g. video encoding or image processing) will be a bottleneck in and of itself if used with Node.js)

2. What advantages does Node.js offer?

A solution like Node.js didn’t gain its popularity just via a cool logo — here are the crucial features that make Node.js so great:

  • Node.js’ ease of use makes it a great option for prototyping and agile development, while its brevity prevents its users from writing too much code (e.g. a server can be up and running in just 16 lines of JS code!)
  • Its non-blocking I/O model allows creating fast and highly-scalable services.
  • “JavaScript everywhere” approach: Node.js allows JavaScript developers to utilize their expertise (e.g. front-end skill set) to become full-stack developers (and receive higher pay); additionally, this allows for cleaner code as the developer will use the same naming conventions and best practices across the board. Hint: reading these JavaScript Interview Questions (then following it up with Part 2) will actually aid your Node.js skills! 😉
  • A large amount of open-source libraries which can help the developer save a lot of time by not creating features or building blocks themselves.

Unfortunately, Node.js is not without its flaws. Its main caveat, poor performance in CPU-heavy tasks, comes from its asynchronous nature. Another problem is callback hell which happens when a number of asynchronous operations are executed.

Top 15 Node.js Interview Questions | Theory and Practice for 2019

3. What are the go-to Node.js frameworks?

To use Node.js in different spheres effectively, we have a wide range of frameworks to choose from. Some of the best include:

  • Express.js: used to create web apps with Node.js. Utilizes the MVC model.
  • Meteor.js: for building reactive web/mobile apps (supporting iOS, Android, desktop, and web versions)
  • Socket.io: used for creating real-time apps.
  • Koa.js: utilizing ES2017 async features, it’s used to build web apps and APIs.
  • MEAN.io: a bundle of open-source solutions that form a framework for creating web apps.

4. Can callback hell be avoided?

Like many life problems, this one can also be solved via writing better code. 🙂

  • Avoid nameless functions — besides creating a cleaner code, it also allows the developer to move and reference them using their descriptive names.
  • As Isaac Schlueter, creator of npm and member of Node.js team, puts it: Write small modules that each do one thing, and assemble them into other modules that do a bigger thing. — this allows the developer to avoid rewriting their code.
  • Handle each error: with a large number of possible errors, a good practice is to reserve the first argument for an error — that way, the developer will remember to handle any errors that pop up.

5. How does Event Loop work in Node.js?

Top 15 Node.js Interview Questions | Theory and Practice for 2019
Contemporary art of 2019

The Event loop manages each asynchronous callback. As Node.js utilizes a single thread and is event-driven, the developer can include specific listeners to an event — when the said event goes off, the listener will execute the callback we provided. Node.js executes one operation and doesn’t stop to wait for the output; instead, it keeps on executing other code parts. After an operation is executed, the output is received and the callback function is run — in this case, each of the callback functions is queued in this Event Loop and run consecutively.

6. How does the non-blocking I/O model function?

Unlike many other environments (in relation to Java or PHP), Node.js utilizes a non-blocking I/O model. This means that operation A gets executed, but does not prevent further operations (B, C, D…) from being executed before it finishes first. This allows the developer to fully use CPU’s power (although only a single thread)

7. Which tool can be used to deploy Node.js application on the server?

Node.js offers a variety of different tools that enable a given app to be deployed on a server and keep it running. The optimal solution is pm2 as it provides great features like:

  • Running a number of instances of an application on the same port.
  • Running an app in cluster mode.
  • A built-in load balancer.
  • Managing deployment of a number of apps via a single config file.

8. How can Node.js applications be debugged?

Top 15 Node.js Interview Questions | Theory and Practice for 2019
Begone, bugs!

There are quite a few debugging options available to Node.js developers:

  • VS Code’s debugger can be used via running a Node.js app with the inspect flag: $ node — inspect .js.
  • Chrome DevTools debugger can also be used — working just like with client-side JavaScript.
  • Node-inspector with the following option: $ node-debug app.js, loading the Inspector in developer’s browser of choice.

9. How to secure a Node.js app?

With Node.js being the project’s backbone, it’s crucial to ensure that all security policies are in place.

  • Node.js debugger is provided with full access to the Node.js execution environment — this means that a hacker can access its port and run their own code, acting as a Node.js process; therefore, the developer should make sure that the debug port info is never leaked.
  • Authentication: checking the user’s identity and verifying their access level.
  • Using Node.js security tools: helmet (sets HTTP headers), csurf (verifies correct tokens in incoming requests), node rate limiter (protects from brute force attacks via controlling the rate of repeated requests), and cors (enables cross-origin resource sharing).

Coding

Of course, no technical interview is complete without some real coding challenges — so let’s see how a remote Node.js developer will approach these!

10. How to print command line arguments passed to the script?

Sample command:
node script.js a b=1 23
Sample output:

a
b=1
23

Answer:

var i;
if(process.argv.length > 2) {
  for(i=2; i<process.argv.length; i++) {
    console.log(process.argv[i]);
  }
}

11. What is wrong with this code?

function foo(err, callback) {
    if (err) {
        callback(err);
    }
    callback();
}

Answer:
Calling the callback is not stopping the method from completing the execution. It will just move on to calling next callback(). The code can be corrected in this way:

function foo(err, callback) {
    if (err) {
        return callback(err);
    }
    callback();
}

12. There are 3 files in the directory “nums”: 1.txt (1 byte), 2.txt (2 bytes), 3.txt (3 bytes) What will the console output look like?

var fs = require('fs');
var path = 'nums';
fs.readdir(path, function(err, items) {
    for (var i=0; i<items.length; i++) {
        var file = path + '/' + items[i];
        console.log(file);
        fs.stat(file, function(err, stats) {
            console.log(file);
            console.log(stats['size']);
        });
    }
});

Answer:

nums/1.txt
nums/2.txt
nums/3.txt
nums/3.txt
1
nums/3.txt
2
nums/3.txt
3

13. What is the output of this code?

var events = require('events');
var onceMoreEventEmitter = new events.EventEmitter();

onceMoreEventEmitter.once('once', function() { console.log('once'); });
onceMoreEventEmitter.on('more', function() { console.log('more'); });
onceMoreEventEmitter.emit('once');
onceMoreEventEmitter.emit('more');
onceMoreEventEmitter.emit('once');
onceMoreEventEmitter.emit('more');

Answer:

once
more
more

14. Create a simple http server listening at port 3000 to serve video

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'video/mp4'});
  var rstream = fs.createReadStream('video.mp4');
  rstream.pipe(res);
}).listen(3000);

15. Create a simple web server that can read a given file on a given disk via “readFile” function

var http = require("http");
var fs = require('fs');
var port = 3000;
var serverUrl = "127.0.0.1";
var counter = 0;

var server = http.createServer(function(req, res) {

  counter++;
  console.log("Request: " + req.url + " (" + counter + ")");

  if(req.url == "/sample.html") {

    fs.readFile("sample.html", function(err, text){
      res.setHeader("Content-Type", "text/html");
      res.end(text);
    });
    return;

  }

  res.setHeader("Content-Type", "text/html");
  res.end("<p>Hello World. Request counter: " + counter + ".</p>");

});

console.log("Starting web server at " + serverUrl + ":" + port);
server.listen(port, serverUrl);

Conclusion

Although technical interviews often seem like the ultimate challenge, with just enough effort and perseverance, you can become the best remote Node.js developer — so here’s to that! ⭐

One Reply to “Top 15 Node.js Interview Questions | Theory and Practice for 2019”

  1. stephenjesus 5 years ago

    I think it’s useful for web developers and programmers. For your convenience, you can have everything in one place.

    http://onlinedevtools.in

Leave a Reply