Node.js interview questions
17 questions with answers. 690 open jobs in India ask for Node.js.
How can you avoid callback hells?Advanced
Refactoring the functions to return promises and using
async/awaitis usually the best option. Instead of supplying the functions with callbacks that cause deep nesting, they return a promise that can beawaited and will be resolved once the data has arrived, allowing the next line of code to be evaluated in a sync-like fashion.The above code can be restructured like so:
async function asyncAwaitVersion() { const a = await getData() const b = await getMoreData(a) const c = await getMoreData(b) const d = await getMoreData(c) const e = await getMoreData(d) // ... }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 (from v7 on)
Good to hear
- As an efficient JavaScript developer, you have to avoid the constantly growing indentation level, produce clean and readable code and be able to handle complex flows.
From 30 seconds of interviews (MIT)
NodeJS often uses a callback pattern where if an error is encountered during execution, this error is passed as the first argument to the callback. What are the advantages of this pattern?Intermediate
Advantages include:
- Not needing to process data if there is no need to even reference it
- Having a consistent API leads to more adoption
- Ability to easily adapt a callback pattern that will lead to more maintainable code
As you can see from below example, the callback is called with null as its first argument if there is no error. However, if there is an error, you create an Error object, which then becomes the callback's only parameter. The callback function allows a user to easily know whether or not an error occurred.
This practice is also called the Node.js error convention, and this kind of callback implementations are called error-first callbacks.
var isTrue = function(value, callback) { if (value === true) { callback(null, "Value was true.") } else { callback(new Error("Value is not true!")) } } var callback = function(error, retval) { if (error) { console.log(error) return } console.log(retval) } isTrue(false, callback) isTrue(true, callback) /* { stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'Value is not true!' } Value was true. */Good to hear
- This is just a convention. However, you should stick to it.
From 30 seconds of interviews (MIT)
What is the event loop in Node.js?Advanced
The event loop handles all async callbacks. Callbacks are queued in a loop, while other code runs, and will run one by one when the response for each one has been received.
Good to hear
- The event loop allows Node.js to perform non-blocking I/O operations, despite the fact that JavaScript is single-threaded
From 30 seconds of interviews (MIT)
What is REST?Intermediate
REST (REpresentational State Transfer) is a software design pattern for network architecture. A RESTful web application exposes data in the form of information about its resources.
Generally, this concept is used in web applications to manage state. With most applications, there is a common theme of reading, creating, updating, and destroying data. Data is modularized into separate tables like
posts,users,comments, and a RESTful API exposes access to this data with:- An identifier for the resource. This is known as the endpoint or URL for the resource.
- The operation the server should perform on that resource in the form of an HTTP method or verb. The common HTTP methods are GET, POST, PUT, and DELETE.
Here is an example of the URL and HTTP method with a
postsresource:- Reading:
/posts/=> GET - Creating:
/posts/new=> POST - Updating:
/posts/:id=> PUT - Destroying:
/posts/:id=> DELETE
Good to hear
- Alternatives to this pattern like GraphQL
From 30 seconds of interviews (MIT)
What's the difference between tilde(~) and caret(^) in package.json?
See the NPM docs and semver docs:
~version“Approximately equivalent to version”, will automatically update you to all future patch versions that are backwards-compatible, without incrementing the minor version.~1.2.3will use releases from1.2.3to <1.3.0.^version“Compatible with version”, will automatically update you to all future minor/patch versions that are backwards-compatible, without incrementing the major version.^1.2.3will use releases from1.2.3to <2.0.0.
See Comments below for exceptions, in particular for pre-one versions, such as ^0.2.3
From Stack Overflow: asked by Fizer Khan, answered by jgillich (CC BY-SA 4.0)
What's the difference between dependencies, devDependencies, and peerDependencies in NPM package.json file?
Summary of important behavior differences:
dependenciesare installed on both:npm installfrom a directory that containspackage.jsonnpm install $packageon any other directory
devDependenciesare:- also installed on
npm installon a directory that containspackage.json, unless you pass the--productionflag (go upvote Gayan Charith's answer), or if theNODE_ENV=productionenvironment variable is set - not installed on
npm install "$package"on any other directory, unless you give it the--devoption. - are not installed transitively.
- also installed on
-
- before 3.0: are always installed if missing, and raise an error if multiple incompatible versions of the dependency would be used by different dependencies.
- expected to start on 3.0 (untested): give a warning if missing on
npm install, and you have to solve the dependency yourself manually. When running, if the dependency is missing, you get an error (mentioned by @nextgentech) This explains it nicely: https://flaviocopes.com/npm-peer-dependencies/ - in version 7 peerDependencies are automatically installed unless an upstream dependency conflict is present that cannot be automatically resolved
Transitivity (mentioned by Ben Hutchison):
dependenciesare installed transitively: if A requires B, and B requires C, then C gets installed, otherwise, B could not work, and neither would A.devDependenciesis not installed transitively. E.g. we don't need to test B to test A, so B's testing dependencies can be left out.
Related options not discussed here:
bundledDependencieswhich is discussed on the following question: Advantages of bundledDependencies over normal dependencies in npmoptionalDependencies(mentioned by Aidan Feldman)
devDependencies
dependenciesare required to run,devDependenciesonly to develop, e.g.: unit tests, CoffeeScript to JavaScript transpilation, minification, ...If you are going to develop a package, you download it (e.g. via
git clone), go to its root which containspackage.json, and run:npm installRead the rest at the sourceFrom Stack Overflow: asked by Vitalii Korsakov, answered by Ciro Santilli OurBigBook.com (CC BY-SA 4.0)
Do I commit the package-lock.json file created by npm 5?
Yes,
package-lock.jsonis intended to be checked into source control. If you're using npm 5+, you may see this notice on the command line:created a lockfile as package-lock.json. You should commit this file.According tonpm help package-lock.json:package-lock.jsonis automatically generated for any operations where npm modifies either thenode_modulestree, orpackage.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.This file is intended to be committed into source repositories, and serves various purposes:
Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.
Provide a facility for users to "time-travel" to previous states of
node_moduleswithout having to commit the directory itself.To facilitate greater visibility of tree changes through readable source control diffs.
And optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages.
One key detail about
package-lock.jsonis that it cannot be published, and it will be ignored if found in any place other than the toplevel package. It shares a format with npm-shrinkwrap.json, which is essentially the same file, but allows publication. This is not recommended unless deploying a CLI tool or otherwise using the publication process for producing production packages.If both
package-lock.jsonandnpm-shrinkwrap.jsonare present in the root of a package,package-lock.jsonwill be completely ignored.From Stack Overflow: asked by rink.attendant.6, answered by vine77 (CC BY-SA 4.0)
How to decide when to use Node.js?
You did a great job of summarizing what's awesome about Node.js. My feeling is that Node.js is especially suited for applications where you'd like to maintain a persistent connection from the browser back to the server. Using a technique known as "long-polling", you can write an application that sends updates to the user in real time. Doing long polling on many of the web's giants, like Ruby on Rails or Django, would create immense load on the server, because each active client eats up one server process. This situation amounts to a tarpit attack. When you use something like Node.js, the server has no need of maintaining separate threads for each open connection.
This means you can create a browser-based chat application in Node.js that takes almost no system resources to serve a great many clients. Any time you want to do this sort of long-polling, Node.js is a great option.
It's worth mentioning that Ruby and Python both have tools to do this sort of thing (eventmachine and twisted, respectively), but that Node.js does it exceptionally well, and from the ground up. JavaScript is exceptionally well situated to a callback-based concurrency model, and it excels here. Also, being able to serialize and deserialize with JSON native to both the client and the server is pretty nifty.
I look forward to reading other answers here, this is a fantastic question.
It's worth pointing out that Node.js is also great for situations in which you'll be reusing a lot of code across the client/server gap. The Meteor framework makes this really easy, and a lot of folks are suggesting this might be the future of web development. I can say from experience that it's a whole lot of fun to write code in Meteor, and a big part of this is spending less time thinking about how you're going to restructure your data, so the code that runs in the browser can easily manipulate it and pass it back.
Here's an article on Pyramid and long-polling, which turns out to be very easy to set up with a little help from gevent: TicTacToe and Long Polling with Pyramid.
From Stack Overflow: asked by Legend, answered by Benson (CC BY-SA 3.0)
What is the purpose of Node.js module.exports and how do you use it?
module.exportsis the object that's actually returned as the result of arequirecall.The
exportsvariable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:let myFunc1 = function() { ... }; let myFunc2 = function() { ... }; exports.myFunc1 = myFunc1; exports.myFunc2 = myFunc2;to export (or "expose") the internally scoped functions
myFunc1andmyFunc2.And in the calling code you would use:
const m = require('./mymodule'); m.myFunc1();where the last line shows how the result of
requireis (usually) just a plain object whose properties may be accessed.NB: if you overwrite
exportsthen it will no longer refer tomodule.exports. So if you wish to assign a new object (or a function reference) toexportsthen you should also assign that new object tomodule.exportsIt's worth noting that the name added to the
exportsobject does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:let myVeryLongInternalName = function() { ... }; exports.shortName = myVeryLongInternalName; // add other objects, functions, as requiredfollowed by:
const m = require('./mymodule'); m.shortName(); // invokes module.myVeryLongInternalNameFrom Stack Overflow: asked by mrwooster, answered by Alnitak (CC BY-SA 4.0)
Using Node.js require vs. ES6 import/export
Update
Since Node.js v12 (April 2019), support for ES modules is enabled by default, and since Node.js v15 (October 2020) it's stable (see here). Files, including Node.js modules, must either end in
.mjsor the nearestpackage.jsonfile must contain"type": "module". The Node.js documentation has a ton more information, also about interoperability between CommonJS and ES modules.Performance-wise there is always the chance that newer features are not as well optimized as existing features. However, since module files are only evaluated once, the performance aspect can probably be ignored. In the end, you have to run benchmarks to get a definite answer anyway.
ES modules can be loaded dynamically via the
import()function. Unlikerequire, this returns a promise.Previous answer
Are there any performance benefits to using one over the other?
Keep in mind that there is no JavaScript engine yet that natively supports ES6 modules. You said yourself that you are using Babel. Babel converts
importandexportdeclaration to CommonJS (require/module.exports) by default anyway. So even if you use ES6 module syntax, you will be using CommonJS under the hood if you run the code in Node.js.There are technical differences between CommonJS and ES6 modules, e.g., CommonJS allows you to load modules dynamically. ES6 doesn't allow this, but there is an API in development for that.
Since ES6 modules are part of the standard, I would use them.
From Stack Overflow: asked by kpimov, answered by Felix Kling (CC BY-SA 4.0)
What is the difference between --save and --save-dev?
The difference between
--saveand--save-devmay not be immediately noticeable if you have tried them both on your own projects. So here are a few examples...Let's say you were building an app that used the moment package to parse and display dates. Your app is a scheduler so it really needs this package to run, as in: cannot run without it. In this case you would use
npm install moment --saveThis would create a new value in your package.json
"dependencies": { ... "moment": "^2.17.1" }When you are developing, it really helps to use tools such as test suites and may need jasmine-core and karma. In this case you would use
npm install jasmine-core --save-dev npm install karma --save-devThis would also create a new value in your package.json
"devDependencies": { ... "jasmine-core": "^2.5.2", "karma": "^1.4.1", }You do not need the test suite to run the app in its normal state, so it is a
--save-devtype dependency, nothing more. You can see how if you do not understand what is really happening, it is a bit hard to imagine.Taken directly from NPM docs docs#dependencies
Dependencies
Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string that has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.
Please do not put test harnesses or transpilers in your dependencies object. See devDependencies, below.
Even in the docs, it asks you to use
--save-devfor modules such as test harnesses.From Stack Overflow: asked by nfort, answered by Michael Bruce (CC BY-SA 4.0)
Is there a way to get the version from the 'package.json' file in Node.js code?
I found that the following code fragment worked best for me. Since it uses
requireto load thepackage.json, it works regardless of the current working directory.var pjson = require('./package.json'); console.log(pjson.version);A warning, courtesy of @Pathogen:
Doing this with Browserify has security implications.
Be careful not to expose yourpackage.jsonto the client, as it means that all your dependency version numbers, build and test commands and more are sent to the client.
If you're building server and client in the same project, you expose your server-side version numbers too. Such specific data can be used by an attacker to better fit the attack on your server.From Stack Overflow: asked by Abhik Bose Pramanik, answered by Mark Wallace (CC BY-SA 4.0)
What is "export default" in JavaScript?
It's part of the ES6 module system, described here. There is a helpful example in that documentation, also:
If a module defines a default export:
// foo.js export default function() { console.log("hello!") }then you can import that default export by omitting the curly braces:
import foo from "foo"; foo(); // hello!Update: As of June 2015, the module system is defined in §15.2 and the
exportsyntax in particular is defined in §15.2.3 of the ECMAScript 2015 specification.From Stack Overflow: asked by damphat, answered by p.s.w.g (CC BY-SA 4.0)
Using async/await with a forEach loop
Sure the code does work, but I'm pretty sure it doesn't do what you expect it to do. It just fires off multiple asynchronous calls, but the
printFilesfunction does immediately return after that.Reading in sequence
If you want to read the files in sequence, you cannot use
forEachindeed. Just use a modernfor … ofloop instead, in whichawaitwill work as expected:async function printFiles () { const files = await getFilePaths(); for (const file of files) { const contents = await fs.readFile(file, 'utf8'); console.log(contents); } }Reading in parallel
If you want to read the files in parallel, you cannot use
forEachindeed. Each of theasynccallback function calls does return a promise, but you're throwing them away instead of awaiting them. Just usemapinstead, and you can await the array of promises that you'll get withPromise.all:async function printFiles () { const files = await getFilePaths(); await Promise.all(files.map(async (file) => { const contents = await fs.readFile(file, 'utf8') console.log(contents) })); }From Stack Overflow: asked by Saad, answered by Bergi (CC BY-SA 4.0)
How do I pass command line arguments to a Node.js program and receive them?
Standard Method (no library)
The arguments are stored in
process.argvHere are the node docs on handling command line args:
process.argvis an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.// print process.argv process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); });This will generate:
$ node process-2.js one two=three four 0: node 1: /Users/mjr/work/node/process-2.js 2: one 3: two=three 4: fourFrom Stack Overflow: asked by milkplus, answered by MooGoo (CC BY-SA 4.0)
How can I update each dependency in package.json to the latest version?
It looks like npm-check-updates is the only way to make this happen now.
npm i -g npm-check-updates ncu -u npm installOr using npx (so you don't have to install a global package):
npx npm-check-updates -u npm installOn npm <3.11:
Simply change every dependency's version to
*, then runnpm update --save. (Note: broken in recent (3.11) versions of npm).Before:
"dependencies": { "express": "*", "mongodb": "*", "underscore": "*", "rjs": "*", "jade": "*", "async": "*" }After:
"dependencies": { "express": "~3.2.0", "mongodb": "~1.2.14", "underscore": "~1.4.4", "rjs": "~2.10.0", "jade": "~0.29.0", "async": "~0.2.7" }Of course, this is the blunt hammer of updating dependencies. It's fine if—as you said—the project is empty and nothing can break.
On the other hand, if you're working in a more mature project, you probably want to verify that there are no breaking changes in your dependencies before upgrading.
To see which modules are outdated, just run
npm outdated. It will list any installed dependencies that have newer versions available.For Yarn specific solution, refer to this Stack Overflow answer.
From Stack Overflow: asked by Raine Revere, answered by josh3736 (CC BY-SA 4.0)
How to exit in Node.js?
Call the global
processobject'sexitmethod:process.exit()process.exit([exitcode])Ends the process with the specified
code. If omitted, exit with a 'success' code0.To exit with a 'failure' code:
process.exit(1);The shell that executed node should see the exit code as
1.From Stack Overflow: asked by 700 Software, answered by Pero P. (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- 30 seconds of interviewsby Stefan Feješ and the 30 seconds of interviews contributorsMIT, © 2018 Stefan Feješ4 questions
- Stack Overflowby its contributors, named on each answerCC BY-SA13 questions