NodeJS Interview Questions

  • Home
  • NodeJS Interview Questions

Node.JS Interview Questions

Dear readers, these Node.JS Interview Questions are specially designed so that you know the nature of the questions you may encounter during your interview on Node.JS. In my experience, good interviewers do not plan to make any particular questions during their interview, usually the questions start with some basic concepts of the topic and then continue to be based on a broader discussion and what they answer:

1. What is Node.js? Where can you use it?

Node.js is a server side scripting based on Google’s V8 JavaScript engine. It is used to build scalable programs especially web applications that are computationally simple but are frequently accessed.You can use Node.js in developing I/O intensive web applications like video streaming sites. You can also use it for developing: Real-time web applications, Network applications, General-purpose applications and Distributed systems.

2.Why use Node.js?

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

  1. It is generally fast
  2. It almost never blocks
  3. It offers a unified programming language and data type
  4. Everything is asynchronous
  5. It yields great concurrency

 

3.What are the features of Node.js?

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.

4.How else can the JavaScript code below be written using Node.Js to produce the same output?

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

5.How do you update NPM to a new version in Node.js?

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

6.Why is Node.js Single-threaded?

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

7.Explain callback in Node.js.

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.

8.What is callback hell in Node.js?

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

9.How do you prevent/fix callback hell?

The three ways to prevent/fix callback hell are:

  • Handle every single error
  • Keep your code shallow
  • Modularize – split the callbacks into smaller, independent functions that can be called with some parameters then joining them to achieve desired results.

The first level of improving the code above might be:

var logError = function(error){
if(!error){
console.log("success!!");
}else{
console.log("error");
}
},
updateTransaction = function(t){
query("UPDATE transactions SET value = " + (t.value*0.1) + " WHERE id=" + t.id, logError);
},
handleTransactions = function(transactions){
transactions.each(updateTransaction);
},
handleClient = function(id){
query("SELECT * FROM transactions WHERE clientId=" + id, handleTransactions);
};

query("SELECT clientId FROM clients WHERE clientName='picanteverde';",handleClient);

You can also use Promises, Generators and Async functions to fix callback hell.

Continue reading Node.JS Interview Questions…………..

10.Explain the role of REPL in Node.js.

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.

11.Name the types of API functions in Node.js.

There are two types of functions in Node.js.:

  • Blocking functions – In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously

For example:
const fs = require(‘fs’);
const data = fs.readFileSync(‘/file.md’); // blocks here until file is read
console.log(data);
// moreWork(); will run after console.log

The second line of code blocks the execution of additional JavaScript until the entire file is read. moreWork () will only be called after Console.log

  • Non-blocking functions – In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted.  Non-blocking functions execute asynchronously.

For example:

const fs = require(‘fs’);
fs.readFile(‘/file.md’, (err, data) => {
if (err) throw err;
console.log(data);
});
// moreWork(); will run before console.log

Since fs.readFile () is non-blocking, moreWork () does not have to wait for the file read to complete before being called. This allows for higher throughput.

12.Which is the first argument typically passed to a Node.js callback handler?

Typically, the first argument to any callback handler is an optional error object. The argument is null or undefined if there is no error.

Error handling by a typical callback handler could be as follows:

function callback(err, results) {
// usually we’ll check for the error before handling results
if(err) {
// handle error somehow and return
}
// no error, perform standard callback handling
}

13.What are the functionalities of NPM in Node.js?

NPM (Node package Manager) provides two functionalities:

  1. Online repository for Node.js packages
  2. Command line utility for installing packages, version management and dependency management of Node.js packages

 

14.What is the difference between Node.js and Ajax?

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.

15.Explain chaining in Node.js.

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

16.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 the reading operation
  • to facilitate the writing operation
  • to facilitate both read and write operations
  • is a form of Duplex stream that performs computations based on the available input

 

17.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:

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

 

18.What are Globals in Node.js?

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

  • Global– it represents the Global namespace object and acts as a container for all otherobjects.
  • 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.

 

19.What is the difference between AngularJS and Node.js?

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

20.Why is consistent style important and what tools can be used to assure it?

Consistent style helps team members modify projects easily without having to get used to a new style every time. Tools that can help include Standard and ESLint.

21.What is an error-first callback?

Error-first callbacks are used to pass errors and data as well. You have to pass the error as the first parameter, and it has to be checked to see if something went wrong. Additional arguments are used to pass data.

fs.readFile(filePath, function(err, data) {

if (err) {

// handle the error, the return is important here

// so execution stops here

return console.log(err)

}

// use the data object

console.log(data)

})

22.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(note that it is only available in the latest v7 release and not in the LTS version – you can read our experimental async/await how-to here)

 

23.How to avoid callback hells?

A: modularization, control flow libraries, generators with promises, async/await

24.What are Promises?

Promises are a concurrency primitive, first described in the 80s. Now they are part of most modern programming languages to make your life easier. Promises can help you better handle async operations.

An example can be the following snippet, which after 100ms prints out the resultstring to the standard output. Also, note the catch, which can be used for error handling. Promises are chainable.

new Promise((resolve, reject) => {

setTimeout(() => {

resolve(‘result’)

}, 100)

})

.then(console.log)

.catch(console.error)

25.What tools can be used to assure consistent style? Why is it important?

When working in a team, consistent style is important, so team members can modify more projects easily, without having to get used to a new style each time.

Also, it can help eliminate programming issues using static analysis.

Tools that can help:

If you’d like to be even more confident, I suggest you to learn and embrace the JavaScript Clean Coding principles as well!

26.What’s a stub? Name a use case!

Stubs are functions/programs that simulate the behaviors of components/modules. Stubs provide canned answers to function calls made during test cases.

An example can be writing a file, without actually doing so.

var fs = require(‘fs’)

var writeFileStub = sinon.stub(fs, ‘writeFile’, function (path, data, cb) {

return cb(null)

})

expect(writeFileStub).to.be.called

writeFileStub.restore()

27.What’s a test pyramid? Give an example!

A test pyramid describes the ratio of how many unit tests, integration tests and end-to-end test you should write.

An example for an HTTP API may look like this:

  • lots of low-level unit tests for models (dependencies are stubbed),
  • fewer integration tests, where you check how your models interact with each other (dependencies are not stubbed),
  • less end-to-end tests, where you call your actual endpoints (dependenciesare not stubbed).

 

28.What’s your favorite HTTP framework and why?

There is no right answer for this. The goal here is to understand how deeply one knows the framework she/he uses. Tell what are the pros and cons of picking that framework.

29.When are background/worker processes useful? How can you handle worker tasks?

Worker processes are extremely useful if you’d like to do data processing in the background, like sending out emails or processing images.

There are lots of options for this like RabbitMQ or Kafka.

30.How can you secure your HTTP cookies against XSS attacks?

XSS occurs when the attacker injects executable JavaScript code into the HTML response.

To mitigate these attacks, you have to set flags on the set-cookie HTTP header:

  • HttpOnly– this attribute is used to help prevent attacks such as cross-site scripting since it does not allow the cookie to be accessed via JavaScript.
  • secure– this attribute tells the browser to only send the cookie if the request is being sent over HTTPS.

So it would look something like this: Set-Cookie: sid=<cookie-value>; HttpOnly. If you are using Express, with express-cookie session, it is working by default.

31.How can you make sure your dependencies are safe?

When writing Node.js applications, ending up with hundreds or even thousands of dependencies can easily happen.
For example, if you depend on Express, you depend on 27 other modules directly, and of course on those dependencies’ as well, so manually checking all of them is not an option!

The only option is to automate the update / security audit of your dependencies. For that there are free and paid options:

Node.js Interview Puzzles

The following part of the article is useful if you’d like to prepare for an interview that involves puzzles, or tricky questions.

32.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 the 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)

If you have to debug a huge codebase, and you don’t know which Promise can potentially hide an issue, you can use the unhandledRejection hook. It will print out all unhandled Promise rejections.

process.on(‘unhandledRejection’, (err) => {

console.log(err)

})

33.What’s wrong with the following code snippet?

function checkApiKey (apiKeyFromDb, apiKeyReceived) {

if (apiKeyFromDb === apiKeyReceived) {

return true

}

return false

}

The Solution

When you compare security credentials it is crucial that you don’t leak any information, so you have to make sure that you compare them in fixed time. If you fail to do so, your application will be vulnerable to timing attacks.

But why does it work like that?

V8, the JavaScript engine used by Node.js, tries to optimize the code you run from a performance point of view. It starts comparing the strings character by character, and once a mismatch is found, it stops the comparison operation. So the longer the attacker has right from the password, the more time it takes.

To solve this issue, you can use the npm module called cryptiles.

function checkApiKey (apiKeyFromDb, apiKeyReceived) {

return cryptiles.fixedTimeComparison(apiKeyFromDb, apiKeyReceived)

}

34.What’s the output of following code snippet?

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)

The Answer

The short answer is 2 – however with this question I’d recommend asking the candidates to explain what will happen line-by-line to understand how they think. It should be something like this:

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

 

Subscribe now

Receive weekly newsletter with educational materials, new courses, most popular posts, popular books and much more!

https://bridgejunks.com/ https://crownmakesense.com/ https://brithaniabookjudges.com/ https://hughesroyality.com/ https://rhythmholic.com/ https://bandar89.simnasfikpunhas.com/ https://www.100calshop.co.il/products/thailand/ https://myasociados.com/ https://solyser.com/ http://konfidence.cz/ https://muscadinepdx.com/ https://bandar89.parajesandinos.com.ve/ https://goremekoop.com/ https://oncoswisscenter.com/ https://www.turunclifehotel.com/bandar89/ https://www.houseofproducts.biz/ https://taimoormphotography.com/
BIJI18 BIJI18 BIJI18