Node Js Interview Questions and Answers

Prepare Node Js interview questions for freshers and experienced candidates. This page includes important questions, answer previews, preparation guidance, related interview topics and cached content for faster page loading.

🟢
83+ Node Js questions available

About Node Js Interview Preparation

Node.js is an event-based, non-blocking, asynchronous I/O framework that uses Google\'s V8 JavaScript engine

For better preparation, read each question carefully, understand the concept, prepare one real example, and connect your answer with your project or work experience.

Node Js Questions List

Quick list of important Node Js interview questions. Detailed answer previews are available below.

  1. What is the purpose of Node.js module.exports and how do you use it?
  2. How do you extract POST data in node.js?
  3. How to decide when to use Node.js?
  4. how to write files in Node.js?
  5. How to debug Node.js applications?
  6. How to get GET (query string) variables in Express on node.js?
  7. What is node.js?
  8. How node.js works?
  9. What do you mean by the term I/O ?
  10. What does event-driven programming mean?
  11. Where can we use node.js?
  12. What is the advantage of using node.js?
  13. What is 'Callback' in node.js?
  14. What does it mean "non-blocking" in node.js?
  15. What are the pros and cons of Node.js?
  16. How to parse JSON using Node.js?
  17. Can we use jQuery with Node.js?
  18. How to get started with Node.js?
  19. Explain Node.js Architecture?
  20. Is Node.js on multi-core machines?
  21. Are you sure node.js execute system command synchronously?
  22. Tell me how to use underscore.js as a template engine?
  23. Do you know what mean stack means?
  24. What is the difference between Node.js vs Ajax?
  25. Mention the steps by which you can async in Node.js?
  26. What are the two arguments that async.queue takes?
  27. Why node.js is quickly gaining attention from JAVA programmers?
  28. Using the event loop what are the tasks that should be done asynchronously?
  29. Explain the steps how "Control Flow" controls the functions calls?
  30. Why Node.js is single threaded?

Question 1: What is the purpose of Node.js module.exports and how do you use it?

Answer: module.exports is the object that's actually returned as the result of a require call.The exports variable 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:var myFunc1 = function() { ... };var myFunc2 = function() { ... };exports.myFunc1 = myFunc1;exports.myFunc2 = myFunc2;to export (or "expose") the internally scoped functions myFunc1 and myFunc2. And in the calling code you would use: var m = require('mymodule');m.myFunc1();where the last line shows how the result of require is (usually) just a plain object whose properties may be accessed. NB: if you ove...

View detailed answer →

Question 2: How do you extract POST data in node.js?

Answer: HTML: <form method="post" action="/"> <input type="text" name="user[name]"> <input type="text" name="user[email]"> <input type="submit" value="Submit"></form> Javascript: app.use(express.bodyParser()); app.post('/', function(request, response){ console.log(request.body.user.name); console.log(request.body.user.email); });

View detailed answer →

Question 3: How to decide when to use Node.js?

Answer: Node.js consider to be used in specific scenario. If your app does not fit into that scenario you should not consider it for your app development.When to use Node.JS If your server side code requires very less cpu cycle. In other world you are doing non blocking operation and does not have heavy algorithm/Job which consumes lots of CPU cycle.If you are from Java Script back ground and comfortable in writing Single Threaded code just like client side JS.When NOT to use Node.JS Your server request is dependent on heavy CPU consuming algorithm/Job.Scalability Consideration with Node.JS Node.JS itself does not utilize all core of underlying syste...

View detailed answer →

Question 4: how to write files in Node.js?

Answer: Currently there are 3 ways to write a file: fs.write(fd, buffer, offset, length, position, [callback]) You need to wait for the callback to ensure that the buffer is written to disk. It's not buffered. fs.writeFile(filename, data, [encoding], [callback]) All data must be stored at the same time; you cannot perform sequential writes. fs.createWriteStream(path, [options]) Creates a WriteStream, which is convenient because you don't need to wait for a callback. But again, it's not buffered. A WriteStream, as the name says, is a stream. A stream by definition is “a buffer” containing data which moves in one direction (source ► d...

View detailed answer →

Question 5: How to debug Node.js applications?

Answer: There are a few tools and ways out there: => Joyent's Guide Joyent now maintains their own debugging guide. It's worth a look. =>Interactive Stack Traces with traceGL =>Profiling with Profiler Note: the profiler module is deprecated, and may not work with version 0.12 of node Install globally npm install -g profilerStart your process with node --prof this will create a v8.log fileBuild nprof by running ~/.nvm/v0.8.22/lib/node_modules/profiler/tools/build-nprofRun ~/.nvm/v0.8.22/lib/node_modules/profiler/nprof this will read the v8.log profile and give you nice ouput. =>CPU and Memory Profiling with NodeTime Install to your applica...

View detailed answer →

Question 6: How to get GET (query string) variables in Express on node.js?

Answer: var url = require('url');var url_parts = url.parse(request.url, true);var query = url_parts.query;

View detailed answer →

Question 7: What is node.js?

Answer: Node.js is a Server side scripting which is used to build scalable programs. Its multiple advantages over other server side languages, the prominent being non-blocking I/O.

View detailed answer →

Question 8: How node.js works?

Answer: Node.js works on a v8 environment, it is a virtual machine that utilizes JavaScript as its scripting language and achieves high output via non-blocking I/O and single threaded event loop.

View detailed answer →

Question 9: What do you mean by the term I/O ?

Answer: i/O is the shorthand for input and output, and it will access anything outside of your application. It will be loaded into the machine memory to run the program, once the application is started.

View detailed answer →

Question 10: What does event-driven programming mean?

Answer: In computer programming, event driven programming is a programming paradigm in which the flow of the program is determined by events like messages from other programs or threads. It is an application architecture technique divided into two sections 1) Event Selection 2) Event Handling

View detailed answer →

Question 11: Where can we use node.js?

Answer: Node.js can be used for the following purposes a)      Web applications ( especially real-time web apps ) b)      Network applications c)       Distributed systems d)      General purpose applications

View detailed answer →

Question 12: What is the advantage of using node.js?

Answer: a)      It provides an easy way to build scalable network programs b)      Generally fast c)       Great concurrency d)      Asynchronous everything e)      Almost never blocks

View detailed answer →

Question 13: What is 'Callback' in node.js?

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

View detailed answer →

Question 14: What does it mean "non-blocking" in node.js?

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

View detailed answer →

Question 15: What are the pros and cons of Node.js?

Answer: 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 i...

View detailed answer →

Question 16: How to parse JSON using Node.js?

Answer: simply use JSON object: JSON.parse(str);JSON.parse. node.js is built on V8, which provides the global object JSON[docs]. The definition of the JSON object is part of the ECMAScript 5 specification.

View detailed answer →

Question 17: Can we use jQuery with Node.js?

Answer: No. It's going to be quite a big effort to port a browser environment to node.Another approach, that I'm currently investigating for unit testing, is to create "Mock" version of jQuery that provides callbacks whenever a selector is called.This way you could unit test your jQuery plugins without actually having a DOM. You'll still have to test in real browsers to see if your code works in the wild, but if you discover browser specific issues, you can easily "mock" those in your unit tests as well.I'll push something to github.com/felixge once it's ready to show. 

View detailed answer →

Question 18: How to get started with Node.js?

Answer: First, learn the core concepts of Node.js:You'll want to understand the asynchronous coding style that Node encourages.Async != concurrent. Understand Node's event loop!Node uses CommonJS-style require() for code loading; it's probably a bit different from what you're used to.Familiarize yourself with Node's standard library.Then, you're going to want to see what the community has to offer:The gold standard for Node package management is NPM.It is a command line tool for managing your project's dependencies.Make sure you understand how Node and NPM interact with your project via the node_modules folder and package.json.NPM is also a registry ...

View detailed answer →

Question 19: Explain Node.js Architecture?

Answer: There are four building blocks that constitute Node.js. First, Node.js encapsulates libuv to handle asynchronous events and Google’s V8 to provide a run-time for JavaScript. Libuv is what abstracts away all of the underlying network and file system functionality on both Windows and POSIX-based systems like Linux, Mac OS X and Unix. The core functionality of Node.js, modules like Assert, HTTP, Crypto, etc., reside in a core library written in JavaScript. The Node.js bindings, written in C++, provide the glue connecting these technologies to each other and to the operating system. 

View detailed answer →

Question 20: Is Node.js on multi-core machines?

Answer: Yes, Node.js is one-thread-per-process. This is a very deliberate design decision and eliminates the need to deal with locking semantics. If you don't agree with this, you probably don't yet realize just how insanely hard it is to debug multi-threaded code. For a deeper explanation of the Node.js process model and why it works this way (and why it will NEVER support multiple threads), read my other post. 

View detailed answer →

Question 21: Are you sure node.js execute system command synchronously?

Answer: There's an excellent module for flow control in node.js called asyncblock. If wrapping the code in a function is OK for your case, the following sample may be considered:var asyncblock = require('asyncblock');var exec = require('child_process').exec;asyncblock(function (flow) {exec('node -v', flow.add());result = flow.wait();console.log(result); // There'll be trailing n in the output// Some other jobsconsole.log('More results like if it were sync...');}); 

View detailed answer →

Question 22: Tell me how to use underscore.js as a template engine?

Answer: Everything you need to know about underscore template is here. Only 3 things to keep in mind:<% %> - to execute some code<%= %> - to print some value in template<%- %> - to print some values with HTML escapedThat's all about it.Simple example:var foo = "blahblah";var tpl = _.template("<h1>Heading for: <= fooo %></h1>");this would be rendered in string <h1>Heading for: blahblah</h1> 

View detailed answer →

Question 23: Do you know what mean stack means?

Answer: MEAN stack stands for MongoDB-Express-AngularJS-NodeJS. First of all, MEAN is JS-only environment. Express is one of the most popular web app frameworks for NodeJS. Node.JS development often goes along noSQL database, like CouchDB or MongoDB, due to their document based structure and JSON notation, which is suitable for all-JS nature of NodeJS. AngularJS is a lightweight framework for building client-side applications. 

View detailed answer →

Question 24: What is the difference between Node.js vs Ajax?

Answer: The difference between Node.js and Ajax is that, Ajax (short for Asynchronous Javascript and XML) is a client side technology, often used for updating the contents of the page without refreshing it. While,Node.js is Server Side Javascript, used for developing server software. Node.js does not execute in the browser but by the server.

View detailed answer →

Question 25: Mention the steps by which you can async in Node.js?

Answer: By following steps you can async Node.js a)      First class functions b)      Function composition c)       Callback Counters d)      Event loops

View detailed answer →

Question 26: What are the two arguments that async.queue takes?

Answer: The two arguments that async.queue takes a)      Task function b)      Concurrency value

View detailed answer →

Question 27: Why node.js is quickly gaining attention from JAVA programmers?

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

View detailed answer →

Question 28: Using the event loop what are the tasks that should be done asynchronously?

Answer: a)      I/O operations b)      Heavy computation c)       Anything requiring blocking

View detailed answer →

Question 29: Explain the steps how "Control Flow" controls the functions calls?

Answer: a)      Control the order of execution b)      Collect data c)       Limit concurrency d)      Call the next step in program

View detailed answer →

Question 30: Why Node.js is single threaded?

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

View detailed answer →

Question 31: What are the two types of API functions in Node.js ?

Answer: The two types of API functions in Node.js are a)      Asynchronous, non-blocking functions b)      Synchronous, blocking functions

View detailed answer →

Question 32: What tool and IDE is used for Node.js?

Answer: =>Nodeclipse Enide Studio=>JetBrains WebStorm=>JetBrains IntelliJ IDEA=>Microsoft Visual Studio with TypeScript=>NoFlo – flow-based programming environment integrated with GNOME APIs

View detailed answer →

Question 33: How to handle the "Unhandled exceptions" in Node.js?

Answer: It can be caught at the "Process level" by attaching a handler for uncaughtException event.Example: process.on('uncaughtException', function(err) { console.log('Caught exception: ' + err); });

View detailed answer →

Question 34: Is Nodejs really Single-Threaded

Answer: Node.js operates on single-thread, but using non-blocking I/O calls allows it to support many concurrent connections. That means node doen't process the requests in parallel but all the back-end stuffs which actually takes lot of time run in parallel.

View detailed answer →

Question 35: Can you explain what is Globals in Nodejs

Answer: Global, Process and Buffer are combinedly termed as Globals.Global : Its a global namespace objectProcess : Its also a global object but it provides essential functionality to transform a synchronous function into a asynchronous callback.Buffer : Raw data is stored in instances of the Buffer class.

View detailed answer →

Question 36: What is the Use of underscore in Nodejs?

Answer: To access the last expression, we have to use the (_) underscore/underline character.

View detailed answer →

Question 37: Can you create Http Server in Nodejs, explain with code

Answer: Yes, we can create Http Server in Nodejs. We can use http-server command to do so.Code :var http = require('http');var requestListener = function (request, response) {  response.writeHead(200, {'Content-Type': 'text/plain'});  response.end('Hello Youn');}var server = http.createServer(requestListener);server.listen(8080); // The port where you want to start with.

View detailed answer →

Question 38: Can you explain the difference between readFile vs createReadStream in Nodejs

Answer: readFile - It will read the file completely into memory before making it available to the User.createReadStream - It will read the file in chunks of the size which is specified before hand.

View detailed answer →

Question 39: Is node js a programming language?

Answer:  As Node. js is not the traditional programming language, but rather a runtime environment, it is easy to learn for both front and back-end developers.  JavaScript is a language. node.js is not a language or a special dialect of JavaScript - it's just a thingamabob that runs normal JavaScript. All browsers have JavaScript engines that run the JavaScript of web pages.  

View detailed answer →

Question 40: What is the use of Nodejs?

Answer:   Node. js is a stage based on Chrome's JavaScript runtime for effectively constructing quick and versatile system applications. Hub. js utilizes an occasion driven, non-blocking I/O model that makes it lightweight and effective, ideal for information serious ongoing applications that stumble into dispersed gadgets.   CHAT API ON TOP OF AN OBJECT DB QUEUED INPUTS DATA STREAMING

View detailed answer →

Question 41: Is node JS frontend or backend?

Answer: Node. js is a runtime environment, which let users choose how to use, whether frontend or backend, and one common language can be used as backend and front end. This environment is entirely based on V8 JavaScript engine. Node.js is utilized "in frontend", which is expected to mean program based code execution, aren't right. Node.js is a backend stage. It is, most actually, a runtime motor based on V8 (with up and coming API support for different JS motors). That has not changed since it's beginning.  

View detailed answer →

Question 42: What is the framework that is used majorly in Node.js today?

Answer: Node.js has multiple frameworks, namely: Hapi.js Express.js Sails.js Meteor.js Derby.js Adonis.js Among these, the most used framework is Express.js for its ability to provide good scalability, flexibility, and minimalism.

View detailed answer →

Question 43: What are the security implementations that are present in Node.js?

Answer: Following are the important implementations for security: Error handling protocols Authentication pipelines

View detailed answer →

Question 44: What is the meaning of a test pyramid?

Answer: A test pyramid is a methodology that is used to denote the number of test cases executed in unit testing, integration testing, and combined testing (in that order). This is maintained to ensure that an ample number of test cases are executed for the end-to-end development of a project.

View detailed answer →

Question 45: What is Libuv?

Answer: Libuv is a widely used library present in Node.js. It is used to complement the asynchronous I/O functionality of Node.js. It was developed in-house and used alongside systems such as Luvit, Julia, and more. Following are some of the features of Libuv: File system event handling Child forking and handling Asynchronous UDP and TCP sockets Asynchronous file handling and operations

View detailed answer →

Question 46: What is the use of middleware in Node.js?

Answer: A middleware is a simple function that has the ability to handle incoming requests and outbound response objects. Middleware is used primarily for the following tasks: Execution of code (of any type) Updating request and response objects Completion of request–response iterations Calling the next middleware

View detailed answer →

Question 47: What are global objects in Node.js?

Answer: Global objects are objects with a scope that is accessible across all of the modules of the Node.js application. There will not be any need to include the objects in every module. One of the objects is declared as global. So, this is done to provide any functions, strings, or objects access across the application.  

View detailed answer →

Question 48: How is a test pyramid implemented using the HTML API in Node.js?

Answer: Test pyramids are implemented by defining the HTML API. This is done using the following: A higher number of unit test cases A smaller number of integration test methods A fewer number of HTTP endpoint test cases  

View detailed answer →

Question 49: Why is a buffer class used in Node.js?

Answer: A buffer class is primarily used as a way to store data in Node.js. This can be considered as a similar implementation of arrays or lists. Here, the class refers to a raw memory location that is not present in the V8 heap structure. The buffer class is global, thereby extending its usage across all the modules of an application.

View detailed answer →

Question 50: Why is ExpressJS used?

Answer: ExpressJS is a widely used framework built using Node.js. Express.js uses a management point that controls the flow of data between servers and server-side applications. Being lightweight and flexible, Express.js provides users with lots of features used to design mobile applications.

View detailed answer →

Question 51: What is the use of the connect module in Node.js?

Answer: The connect module in Node.js is used to provide communication between Node.js and the HTTP module. This also provides easy integration with Express.js, using the middleware modules.

View detailed answer →

Question 52: What are streams in Node.js?

Answer: Streams are a set of data entities in Node.js. These can be considered similar to the working of strings and array objects. Streams are used for continuous read/write operations across a channel. But, if the channel is not available, then all of the data cannot be pushed to the memory at once. Hence, using streams will make it easy to process a large set of data in a continuous manner.  

View detailed answer →

Question 53: What are the types of streams available in Node.js?

Answer: Node.js supports a variety of streams, namely: Duplex (both read and write) Readable streams Writable streams Transform (duplex for modifying data)

View detailed answer →

Question 54: What is the use of REPL in Node.js?

Answer: REPL stands for Read-Eval-Print-Loop. It provides users with a virtual environment to test JavaScript code in Node.js. To launch REPL, a simple command called ‘node’ is used. After this, JavaScript commands can be typed directly into the command line.

View detailed answer →

Question 55: What is meant by tracing in Node.js?

Answer: Tracing is a methodology used to collect all of the tracing information that gets generated by V8, the node core, and the userspace code. All of these are dumped into a log file and are very useful to validate and check the integrity of the information being passed.

View detailed answer →

Question 56: Where is package.json used in Node.js?

Answer: The ‘package.json’ file is a file that contains the metadata about all items in a project. It can also be used as a project identifier and deployed as a means to handle all of the project dependencies.

View detailed answer →

Question 57: What is the difference between readFile and createReadStream in Node.js?

Answer: readFile: This is used to read all of the contents of a given file in an asynchronous manner. All of the content will be read into the memory before users can access it. create ReadStream: This is used to break up the field into smaller chunks and then read it. The default chunk size is 64 KB, and this can be changed as per requirement.

View detailed answer →

Question 58: What is a passport in Node.js?

Answer: Passport is a widely used middleware present in Node.js. It is primarily used for authentication, and it can easily fit into any Express.js-based web application. With every application created, it will require unique authentication mechanisms. This is provided as single modules by using passport, and it becomes easy to assign strategies to applications based on requirements, thereby avoiding any sort of dependencies.

View detailed answer →

Question 59: How does the DNS lookup function work in Node.js?

Answer: The DNS lookup method uses a web address for its parameter and returns the IPv4 or IPv6 record, correspondingly. There are other parameters such as the options that are used to set the input as an integer or an object. If nothing is provided here, both IPv4 and IPv6 are considered. The third parameter is for the callback function. The syntax is: dns.lookup(address, options, callback)

View detailed answer →

Question 60: What is the difference between setImmediate() and setTimeout()?

Answer: The setImmediate() function is meant to execute a single script once the current event loop is complete. The setTimeout() function is used to hold a script and schedule it to be run after a certain time threshold is over. The order of execution will solely depend on the context in which the functions are called. If called from the main module, the timing will be based on the performance of the process.    

View detailed answer →

Question 61: Why do you think you are the right fit for this Node.js role?

Answer: Here, the interviewer wants to know your understanding of the job role and the company architecture and your knowledge on the topic. While answering this question, it would add immensely if you knew the job description in detail and the basic usage of the technology in the company. The answer can be further elaborated on how your interests align with the technology, job, and company.

View detailed answer →

Question 62: Do you have any past Node.js work experience?

Answer: This question is common among Node.js interviews. Make sure to answer it to the best of your abilities, and do not bloat but give your honest experiences and explain how you’ve used Node.js before. This is used as a measure to see if you have had any hands-on experience with the language in a working environment before.

View detailed answer →

Question 63: Do you have any experience working in the same industry like ours?

Answer: With this question, the interviewer is trying to assess if you’ve had any previous work experience or internship experience where you dealt with similar working environments or technologies. This line of questioning can be easily answered based on your previous experiences. Make sure to keep it concise and detailed as required when answering this question.

View detailed answer →

Question 64: Do you have any certification to boost your candidature for this Node.js role?

Answer: t is always advantageous to have a certification in the technology that you’re applying for. This gives the interviewer the impression that you have worked on the technology and that you are serious about using it for your career growth. More than this, it adds immense value to your resume and your knowledge on the topic at the same time.

View detailed answer →

Question 65: What is express.js.

Answer: Express.js is back-end web application framework for node.js. It is the open-source software under mit license. The original author, TJ Holowaychuk, described as a Sinatra-inspired server.                                                                                                                Express is the back-end component of popular development stacks l...

View detailed answer →

Question 66: How many types of API Functions available in Node.js ?

Answer:   There are two types of API functions available in Node.js :1)Asynchronous, non blocking functions .2) Synchronous, blocking functions . Nods.js is an interpreter and run-time enviroment for JS. It is used for perfroming any non -blocking operations in Operating System.Running engine for Node.js is V8(google chrome).

View detailed answer →

Question 67: How can we managed the packages in our Node.js Projects?

Answer: It can be managed by using several packages installer and their configuration files. Maximum usages is NPM and YARN.Both of them provides almost all the libraries of Javascripts With extended features of controlling environment. We can use Package.json and Package-lock.json to maintain version of libraries intsalled in projects.So,there will be no issues in porting the app in different environment.

View detailed answer →

Question 68: What is Callback Hell in Node.js?

Answer: Callback hell is a phenomenon it creates a lot of problems for a JavaScript developer when tries to execute multiple asynchronous operations one after the other. It is called an asynchronous function when some external activity must completed before processing a result. It is called asynchronous . Example : getData(function(a){ getMoreData(a, function(b){ getMoreData(b, function(c){ getMoreData(c, function(d){ getMoreData(d, function(e){ ... }); }); }); }); });

View detailed answer →

Question 69: Which types of applications is Node.js most frequently used?

Answer: Node.js is most frequently and widely used in the following applications:1) Internet of Things2) Real-time collaboration tools3) Real-time chats4) Complex SPAs (Single-Page Applications)5) Streaming applications6) Microservices architecture etc.

View detailed answer →

Question 70: How to I get the GET (query string) variables in Express.js on Node.js?

Answer: First equation to get the variable string (value.query.id) sovar express = require('express');var app = express(); app.get('/', function(req, res){ res.send('id: ' + req.query.id);}); app.listen(3000);   otherwise we can get another equationvar url = require('url');var url_parts = url.parse(request.url, true);var query = url_parts.query;  

View detailed answer →

Question 71: How to install express.js. in mern stack development.

Answer:  create cluster  If we want to install express.js on windows with mongoDB. I gonna go to twerminal and type (npm install express cors dotenv) after some express.js installed in my system we can use it. nodemon is useful create customize web application.

View detailed answer →

Question 72: How to install node.js?

Answer: There have various step to install node.js on windows machine are:-1. Download Node.js Installer for Windows Go to the site https://nodejs.org/en/download/ and download the necessary binary files. ...2. Run the installation Double click on the downloaded .msi file to start the installation. Click the Run button on the first screen to begin the installation.3. Continue with the installation steps In the next screen, click the "Next" button to continue with the installation4. Accept the terms and conditions In the next screen, Accept the license agreement and click on the Next button.5. Set up the path

View detailed answer →

Question 73: Node JS with Express API returning null instead undefined in array items?

Answer: The res.send return a JSON, and undefined is not a valid JSON value, even though it is valid in javascript.

View detailed answer →

Question 74: How do I pass command line arguments to the Node.js program?

Answer: process.argv is 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. Example by code:- // print process.argv process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val);});This will generate: $ node process-2.js one two=three four0: node1: /Users/mjr/work/node/process-2.js2: one3: two=three4: four

View detailed answer →

Question 75: What's the difference between tilde(~) and caret(^) in package.json?

Answer: There have two points to explain the tilde and caret are:- 1. ~version “Approximately equivalent to version”, will update you to all future patch versions, without incrementing the minor version. ~1.2.3 will use releases from 1.2.3 to <1.3.0. 2. ^version “Compatible with version”, will update you to all future minor/patch versions, without incrementing the major version. ^2.3.4 will use releases from 2.3.4 to <3.0.0.

View detailed answer →

Question 76: Remove all child elements of a DOM node in JavaScript?

Answer: An earlier edit to this answer used firstChild, but this is updated to use lastChild as in computer-science, in general, it's significantly faster to remove the last element of a collection than it is to remove the first element (depending on how the collection is implemented).The loop continues to check for firstChild just in case it's faster to check for firstChild than lastChild (e.g. if the element list is implemented as a directed linked-list by the UA). doFoo.onclick = () => { const myNode = document.getElementById("foo"); while (myNode.firstChild) { myNode.removeChild(myNode.lastChild); }}<div id='foo' style="height: 100px; width...

View detailed answer →

Question 77: What is the most efficient way to deep clone an object in the JavaScript?

Answer:  The name of deep cloning is Native deep cloning There's now a JS standard called "structured cloning", that works experimentally in Node 11 and later, will land in browsers, and which has polyfills for existing systems. structuredClone(value)If needed, loading the polyfill first: import structuredClone from '@ungap/structured-clone';  

View detailed answer →

Question 78: How to undo "git commit --amend" done instead of "git commit"?

Answer: If you have pushed the commit to remote and then erroneously amended changes to that commit this will fix your problem. Issue a git log to find the SHA before the commit. (this assumes remote is named origin). Now issue these command using that SHA. git reset --soft <SHA BEFORE THE AMMEND>#you now see all the changes in the commit and the amend undone #save ALL the changes to the stashgit stash git pull origin <your-branch> --ff-only#if you issue git log you can see that you have the commit you didn't want to amend git stash pop#git status reveals only the changes you incorrectly amended #now you can create your new unamended comm...

View detailed answer →

Question 79: What does the "yield" keyword do?

Answer: Below is the example of yield codes are:- >>> def create_generator():... mylist = range(3)... for i in mylist:... yield i*i...>>> mygenerator = create_generator() # create a generator>>> print(mygenerator) # mygenerator is an object!<generator object create_generator at 0xb7555c34>>>> for i in mygenerator:... print(i)014Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once. To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function...

View detailed answer →

Question 80: Execute a command line binary with Node.js?

Answer: For even newer version of Node.js (v13.3.6), the events and calls are similar or identical to older versions, but it's encouraged to use the standard newer language features. Examples: For buffered, non-stream formatted output (you get it all at once), use child_process.exec: const { exec } = require('child_process');exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => { if (err) { // node couldn't execute the command return; } // the *entire* stdout and stderr (buffered) console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`);});    

View detailed answer →

Question 81: What are the options for storing hierarchical data in a relational database?

Answer: My favorite answer is as what the first sentence in this thread suggested. Use an Adjacency List to maintain the hierarchy and use Nested Sets to query the hierarchy. The problem up until now has been that the coversion method from an Adjacecy List to Nested Sets has been frightfully slow because most people use the extreme RBAR method known as a "Push Stack" to do the conversion and has been considered to be way to expensive to reach the Nirvana of the simplicity of maintenance by the Adjacency List and the awesome performance of Nested Sets. As a result, most people end up having to settle for one or the other especially if there are more t...

View detailed answer →

Question 82: How to store Node.js deployment settings/configuration files?

Answer: I use a package.json for my packages and a config.js for my configuration, which looks like: var config = {}; config.twitter = {};config.redis = {};config.web = {}; config.default_stuff = ['red','green','blue','apple','yellow','orange','politics'];config.twitter.user_name = process.env.TWITTER_USER || 'username';config.twitter.password= process.env.TWITTER_PASSWORD || 'password';config.redis.uri = process.env.DUOSTACK_DB_REDIS;config.redis.host = 'hostname';config.redis.port = 6379;config.web.port = process.env.WEB_PORT || 9980; module.exports = config; I use a package.json for my packages and a config.js for my configuration, which looks lik...

View detailed answer →

Question 83: List all in built module of node JS in details

Answer: Node.js has a Multiple built-in modules below which we can use without any installation just need to import.   Module assert Provides a set of assertion tests buffer To handle binary data child_process To run a child process cluster To split a single Node process into multiple processes crypto To handle OpenSSL cryptographic functions dgram Provides implementation of UDP datagram sockets dns To do DNS lookups and name resolution functions domain Deprecated. To handle unhandled errors events To handle events fs To handle the file system http To make Node.js act as an HTTP server https To make Node.js act as an HTTPS server. net To create ...

View detailed answer →
Node Js interview preparation tip: Start with basic definitions, then prepare practical examples, common mistakes, project usage, scenario-based questions and HR discussion points.