What is Node.js? Where can you use it?
Node.js is an open-source, cross-platform JavaScript runtime environment and library to run web applications outside the client’s browser. It is used to create server-side web applications.
Node.js is perfect for data-intensive applications as it uses an asynchronous, event-driven model. You can use 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.
Why use Node.js?
Node.js makes building scalable network programs easy. Some of its advantages include:
- It is generally fast
- It rarely blocks
- It offers a unified programming language and data type
- Everything is asynchronous
- It yields great concurrency
How does Node.js work?
A web server using Node.js typically has a workflow that is quite similar to the diagram illustrated below. Let’s explore this flow of operations in detail.

- Clients send requests to the webserver to interact with the web application. Requests can be non-blocking or blocking:
- Querying for data
- Deleting data
- Updating the data
- Node.js retrieves the incoming requests and adds those to the Event Queue
- The requests are then passed one-by-one through the Event Loop. It checks if the requests are simple enough not to require any external resources
- The Event Loop processes simple requests (non-blocking operations), such as I/O Polling, and returns the responses to the corresponding clients
A single thread from the Thread Pool is assigned to a single complex request. This thread is responsible for completing a particular blocking request by accessing external resources, such as computation, database, file system, etc.
Once the task is carried out completely, the response is sent to the Event Loop that sends that response back to the client.
Node JS Interview Question
Why is Node.js Single-threaded?
Node.js is single-threaded for sync processing. By doing a sync processing on a single-thread under typical web loads, more performance and scalability can be achieved instead of the typical thread-based implementation.
Explain callback in Node.js.
A callback function is called after a given task. It 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.
How would you define the term I/O?
- The term I/O is used to describe any program, operation, or device that transfers data to or from a medium and to or from another medium
- Every transfer is an output from one medium and an input into another. The medium can be a physical device, network, or files within a system
Advance Node JS Interview Question
How is Node.js most frequently used?
Node.js is widely used in the following applications:
- Real-time chats
- Internet of Things
- Complex SPAs (Single-Page Applications)
- Real-time collaboration tools
- Streaming applications
- Microservices architecture
Explain the difference between frontend and backend development?
Front-end | Back-end |
Frontend refers to the client-side of an application | Backend refers to the server-side of an application |
It is the part of a web application that users can see and interact with | It constitutes everything that happens behind the scenes |
It typically includes everything that attributes to the visual aspects of a web application | It generally includes a web server that communicates with a database to serve requests |
HTML, CSS, JavaScript, AngularJS, and ReactJS are some of the essentials of frontend development | Java, PHP, Python, and Node.js are some of the backend development technologies |
What is NPM?
NPM stands for Node Package Manager, responsible for managing all the packages and modules for Node.js.
Node Package Manager provides two main functionalities:
- Provides online repositories for node.js packages/modules, which are searchable on search.nodejs.org
- Provides command-line utility to install Node.js packages and also manages Node.js versions and dependencies
Node JS Interview Question
What are the modules in Node.js?
Modules are like JavaScript libraries that can be used in a Node.js application to include a set of functions. To include a module in a Node.js application, use the require() function with the parentheses containing the module’s name.
Node.js has many modules to provide the basic functionality needed for a web application. Some of them include:
Core Modules | Description |
HTTP | Includes classes, methods, and events to create a Node.js HTTP server |
util | Includes utility functions useful for developers |
fs | Includes events, classes, and methods to deal with file I/O operations |
url | Includes methods for URL parsing |
query string | Includes methods to work with query string |
stream | Includes methods to handle streaming data |
zlib | Includes methods to compress or decompress files |
Why is Node.js preferred over other backend technologies like Java and PHP?
Some of the reasons why Node.js is preferred include:
- Node.js is very fast
- Node Package Manager has over 50,000 bundles available at the developer’s disposal
- Perfect for data-intensive, real-time web applications, as Node.js never waits for an API to return data
- Better synchronization of code between server and client due to same code base
- Easy for web developers to start using Node.js in their projects as it is a JavaScript library
What is the difference between Angular and Node.js?
Angular | Node.js |
It is a frontend development framework | It is a server-side environment |
It is written in TypeScript | It is written in C, C++ languages |
Used for building single-page, client-side web applications | Used for building fast and scalable server-side networking applications |
Splits a web application into MVC components | Generates database queries |
Advance Node JS Interview Question
Which database is more popularly used with Node.js?
MongoDB is the most common database used with Node.js. It is a NoSQL, cross-platform, document-oriented database that provides high performance, high availability, and easy scalability.
What are some of the most commonly used libraries in Node.js?
There are two commonly used libraries in Node.js:
- Express JS – Express is a flexible Node.js web application framework that provides a wide set of features to develop web and mobile applications.
- Mongoose – Mongoose is also a Node.js web application framework that makes it easy to connect an application to a database.
What are the pros and cons of Node.js?
Node.js Pros | Node.js Cons |
Fast processing and an event-based model | Not suitable for heavy computational tasks |
Uses JavaScript, which is well-known amongst developers | Using callback is complex since you end up with several nested callbacks |
Node Package Manager has over 50,000 packages that provide the functionality to an application | Dealing with relational databases is not a good option for Node.js |
Best suited for streaming huge amounts of data and I/O intensive operations | Since Node.js is single-threaded, CPU intensive tasks are not its strong suit |
Node JS Interview Question
What is the command used to import external libraries?
The “require” command is used for importing external libraries. For example – “var http=require (“HTTP”).” This will load the HTTP library and the single exported object through the HTTP variable.
Now that we have covered some of the important beginner-level Node.js interview questions let us look at some of the intermediate-level Node.js interview questions.
What does event-driven programming mean?
An event-driven programming approach uses events to trigger various functions. An event can be anything, such as typing a key or clicking a mouse button. A call-back function is already registered with the element executes whenever an event is triggered.
What is an Event Loop in Node.js?
Event loops handle asynchronous callbacks in Node.js. It is the foundation of the non-blocking input/output in Node.js, making it one of the most important environmental features.
Advance Node JS Interview Question
What is an Event Emitter in Node.js?
- Event Emitter is a class that holds all the objects that can emit events
- Whenever an object from the Event Emitter class throws an event, all attached functions are called upon synchronously
What are the two types of API functions in Node.js?
The two types of API functions in Node.js are:
- Asynchronous, non-blocking functions
- Synchronous, blocking functions
What is the package.json file?
The package.json file is the heart of a Node.js system. This file holds the metadata for a particular project. The package.json file is found in the root directory of any Node application or module
This is what a package.json file looks like immediately after creating a Node.js project using the command: npm init
You can edit the parameters when you create a Node.js project.
Node JS Interview Question
How would you use a URL module in Node.js?
The URL module in Node.js provides various utilities for URL resolution and parsing. It is a built-in module that helps split up the web address into a readable format.
What is the Express.js package?
Express is a flexible Node.js web application framework that provides a wide set of features to develop both web and mobile applications
How do you create a simple Express.js application?
- The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on
- The response object represents the HTTP response that an Express app sends when it receives an HTTP request
Advance Node JS Interview Question
What are streams in Node.js?
Streams are objects that enable you to read data or write data continuously.
There are four types of streams:
Readable – Used for reading operations
Writable − Used for write operations
Duplex − Can be used for both reading and write operations
Transform − A type of duplex stream where the output is computed based on input
How do you install, update, and delete a dependency?
How do you create a simple server in Node.js that returns Hello World?
- Import the HTTP module
- Use create Server function with a callback function using request and response as parameters.
- Type “hello world.”
- Set the server to listen to port 8080 and assign an IP address
Node JS Interview Question
Explain asynchronous and non-blocking APIs in Node.js.
- All Node.js library APIs are asynchronous, which means they are also non-blocking
- A Node.js-based server never waits for an API to return data. Instead, it moves to the next API after calling it, and a notification mechanism from a Node.js event responds to the server for the previous API call.
How do we implement async in Node.js?
As shown below, the async code asks the JavaScript engine running the code to wait for the request.get() function to complete before moving on to the next line for execution.
What is the purpose of module.exports?
A module in Node.js is used to encapsulate all the related codes into a single unit of code, which can be interpreted by shifting all related functions into a single file. You can export a module using the module.exports, which allows it to be imported into another file using a required keyword.
Advance Node JS Interview Question
What is a callback function in Node.js?
A callback is a function called after a given task. This prevents any blocking and enables other code to run in the meantime.
What is REPL in Node.js?
REPL stands for Read Eval Print Loop, and it represents a computer environment. It’s similar to a Windows console or Unix/Linux shell in which a command is entered. Then, the system responds with an output
What is the difference between fork() and spawn() methods in Node.js?
fork() | spawn() |
fork() is a particular case of spawn() that generates a new instance of a V8 engine. | Spawn() launches a new process with the available set of commands. |
Multiple workers run on a single node code base for multiple tasks. | This method doesn’t generate a new V8 instance, and only a single copy of the node module is active on the processor. |
Node JS Interview Question
What is the buffer class in Node.js?
Buffer class stores raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. Buffer class is used because pure JavaScript is not compatible with binary data
What is piping in Node.js?
Piping is a mechanism used to connect the output of one stream to another stream. It is normally used to retrieve data from one stream and pass output to another stream.
What are some of the flags used in the read/write operations in files?
Advance Node JS Interview Question
How do you open a file in Node.js?
What is callback hell?
- Callback hell, also known as the pyramid of doom, is the result of intensively nested, unreadable, and unmanageable callbacks, which in turn makes the code harder to read and debug
- improper implementation of the asynchronous logic causes callback hell
What is a reactor pattern in Node.js?
A reactor pattern is a concept of non-blocking I/O operations. This pattern provides a handler that is associated with each I/O operation. As soon as an I/O request is generated, it is then submitted to a demultiplexer
Node JS Interview Question
What is a test pyramid in Node.js?
Describe Node.js exit codes.
Explain the concept of middleware in Node.js.
Middleware is a function that receives the request and response objects. Most tasks that the middleware functions perform are:
- Execute any code
- Update or modify the request and the response objects
- Finish the request-response cycle
- Invoke the next middleware in the stack
Advance Node JS Interview Question
What are the different types of HTTP requests?
HTTP defines a set of request methods used to perform desired actions. The request methods include:
GET: Used to retrieve the data
POST: Generally used to make a change in state or reactions on the server
HEAD: Similar to the GET method, but asks for the response without the response body
DELETE: Used to delete the predetermined resource
How would you connect a MongoDB database to Node.js?
To create a database in MongoDB:
- Start by creating a Mongo Client object
- Specify a connection URL with the correct IP address and the name of the database you want to create
What is the purpose of NODE_ENV?
Node JS Interview Question
List the various Node.js timing features.
As you prepare for your upcoming job interview, we hope that this comprehensive guide has provided more insight into what types of questions you’ll be asked.
How is Node.js better than other frameworks most popularly used?
- Node.js provides simplicity in development because of its non-blocking I/O and even-based model results in short response time and concurrent processing, unlike other frameworks where developers have to use thread management.
- It runs on a chrome v8 engine which is written in C++ and is highly performant with constant improvement.
- Also since we will use Java script in both the frontend and backend the development will be much faster.
- And at last, there are ample libraries so that we don’t need to reinvent the wheel.
Explain the steps how “Control Flow” controls the functions calls?
- Control the order of execution
- Collect data
- Limit concurrency
- Call the following step in the program.
Advance Node JS Interview Question
Why do you think you are the right fit for this Node.js role?
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.
What is the use of Event Emitter in Node.js?
Every single object in Node.js that emits is nothing but an instance of the Event Emitter class. These objects have a function that is used to allow the attachment between the objects and the named events.
Synchronous attachments of the functions are done when the Event Emitter object emits an event.
How does the DNS lookup function work in Node.js?
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)
Node JS Interview Question
How to get information about a file in Node.js?
The fs.stat function is used to get the required information from a file.
The syntax is as follows:
fs.stat(path, callback)
where,
- Path: The string that has the path to the name
- Callback: The callback function where stats is an object of fs.stats
Next up among these Node.js interview questions, you need to understand about DNS lookup.
What is a passport in Node.js?
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.
What is the use of the crypto module in Node.js?
The crypto module in Node.js is used to provide users with cryptographic functionalities. This provides them with a large number of wrappers to perform various operations such as cipher, decipher, signing, and hashing operations.
Node JS Interview Question
What is the difference between read File and create Read Stream in Node.js?
- read File: 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 Read Stream: 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.
Where is package.json used in Node.js?
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.
What is meant by tracing in Node.js?
Tracing is a methodology used to collect all of the tracing information that gets generated by V8, the node core, and the user space 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.
Advance Node JS Interview Question
What is the use of REPL in Node.js?
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.
What is the use of the connect module in Node.js?
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.
Why is a buffer class used in Node.js?
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.
Node JS Interview Question
How is a test pyramid implemented using the HTML API in Node.js?
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
What are stubs in Node.js?
Stubs are simply functions that are used to assess and analyze individual component behavior. When running test cases, stubs are useful in providing the details of the functions executed.
Why is assert used in Node.js?
Assert is used to explicitly write test cases to verify the working of a piece of code. The following code snippet denotes the usage of assert:
var assert = require('assert');
function add(x, y) {
return x + y;
}
var result = add(3,5);
assert( result === 8, 'three summed with five is eight');
Advance Node JS Interview Question
What are global objects in Node.js?
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.
Next among the Node JS coding questions, you need to take a look at the usage of assets in Node JS.
What is the use of middleware in Node.js?
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
Why does Google use the V8 engine for Node.js?
Google makes use of the V8 engine because it can easily convert JavaScript into a low-level language. This is done to provide high performance during the execution of an application and also to provide users with real-time abilities to work with the application.
Node JS Interview Question
What is Libuv?
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
Next in these Node JS questions, you need to understand the functioning of Google Chrome.
What are the security implementations that are present in Node.js?
Following are the important implementations for security:
- Error handling protocols
- Authentication pipelines
Difference between cluster and child_process modules?
A Cluster is a module of Node.js that contains sets of functions and properties that helps the developers for forking processes through which they can take advantage of the multi-core system.
A child_process can be easily spun using Node’s child_process module and these child processes can easily communicate with each other with the help of a messaging system.
Advance Node JS Interview Question
How to stop master process without suspending all of its child processes?
With the help of the Upstart process management system, you can stop the master process without suspending all of its child processes.
List some features of Express JS.
Some of the main features of Express JS are listed below: –
It is used for setting up middleware’s so as to provide a response to the HTTP or RESTful requests.
With the help of express JS, the routing table can be defined for performing various HTTP operations.
It is also used for dynamically rendering HTML pages which are based on passing arguments to the templates.
It provides each and every feature which is provided by core Node JS.
The performance of Express JS is adequate due to the presence of a thin layer prepared by the Express JS.
It is used for organizing the web applications into the MVC architecture.
Everything from routes to rendering view and performing HTTP requests can be managed by Express JS.
What is the most suitable database used along with Node.js?
Cassandra, CouchDB, MySQL, MongoDB, Neo4j, Oracle, PostgreSQL, and ElasticSearch are some of the databases used along with Node.js. We can install the connection drivers for these Databases with the command npm install driver_name.
However, MongoDB is more suitable for back-end management with Node.js.
Node JS Interview Question
List some of the Node.js libraries often used?
These are as follows:
- Express: It is a web framework for node.js
- Socket.io: It is for event-based real-time communication
- Cors: Node.js pack to provide connect/express middleware
- Passport: It is used to authenticate requests with strategies extensible plugins
- Axios: HTTP client who is Promise based for node.js and browser
- Multer: Handles multipart/form-data and file uploads
- Morgan: A Node.js middleware that is an HTTP request logger
- HTTP: errors – It helps to generate HTTP errors for Connect, Koa, and Express
What is the difference between fs.readFile() and fs.createReadStream() in Node.js?
Node.js uses two ways of reading a file and sending them for execution.
fs.readFile() | fs.createReadStream() |
---|---|
Using file system module, fs.readFile loads entire file you want to manage into the memory, reads entire file before it is sent to client | fs.CreateReadStream reads entire file in chunks of pieces that we specify |
fs.readFile() is useful making advantage for large content and low size disks | Sending data file with fs.createReadStream() becomes faster. |
fs.readFile() is memory intensive for high content data files | fs.createReadStream() is effective in memory efficient way of handling data intensive processing of large data files. |
Describe Timer() module methods in Node.js
Timer module has various methods like setTimeout(), setImmediate(), setInterval().
These are explained below:
- setTimeout() helps schedule code execution after specified interval in milliseconds.
Syntax:
setTimeout(callback, delay_in_ms, args)
- setInterval() helps calling a function at specified interval, once after desired period.
Syntax:
setTimeout()
- setImmediate() execute code at end of current event loop.
Syntax:
setImmediate(callback, args)
Advance Node JS Interview Question
What is the difference between setImmediate() and setTimeout()?
setImmediate(), setTimeout() and process.nextTick() are Node.js functions that control order of executing code in event loop.
- setTimeout() is executed after process.nextTick() i.e. after current code executed and before any I/O events. setTimeout() arranges script run after minimum threshold of milliseconds has completed.
- setImmediate() is executed after setTimeout(), with callback placed in check queue of next cycle of event loop. This command is processed on the check handler phase of the event loop. setImmediate() executes script after current poll phase completes.
Explain Error first callback in Node.js.
Error-first Callback is a function in Node.js used to pass errors and data. The callback is function asynchronous in nature, called after the Ajax request is completed. The error-first Callback function has the first argument as an error object and the second argument is response data that returns on successful response without any error.
Below is the syntax of the error-first callback function:

What is Node.js Libuv library and its uses?
Libuv is asynchronous input/output that comes as libraries with Node.js installation.
Various features Libuv has are listed below:
- Asynchronous
- TCP & UDP sockets
- DNS resolution
- File and file system
- Thread pool
- Signal handling,
- Backed with the full-featured event loop
- Child processes
- File System Events
Node JS Interview Question
Explain the working of Node.js.
Node.js is a runtime environment that has V8 – JavaScript engine, NPM package manager for Node.js, and Libuv libraries.
V8 is a JavaScript engine that converts browser JavaScript and Node.js code into machine code, making JavaScript run everywhere. NPM is a package manager- a package repository that contains library files containing features that can be included in Node.js.
Real-time applications installed on mobile that displays real-time information on request such as Market share prices, or availability of flights, movie tickets, etc. need data (current status). This data can be retrieved from any server using a single thread of Node.js using non-blocking I/O, wherein waiting for information is avoided, can attend multiple requests simultaneously.

Node.js asynchronous feature is utilized when the response from another server returns with the required information, wherein callback function is executed. Hence Node.js is applicable for I/O intensive applications.
Further, to deal with multiple requests, Node.js uses a concept called Libuv – libraries built in C language. These libraries use a system kernel that uses multiple threads for these requests making Node.js run fast.
What is the difference between == and ===?
The == operator checks equality only whereas === checks equality and data type i.e. value must be of same type.
let a = 10;
let b = "10";
console.log(a == b); // It will console true since the values of x and y is the equal.
console.log(a === b); // It will console false because the values of x and y is the equal but data type is different.
When should and shouldn’t you use Node.js?
Node.js is asynchronous, event-driven, non-blocking, and single-threaded. It makes Node a perfect candidate for developing the following types of applications:
- Realtime applications like chat and live update providing applications.
- Streaming applications that stream video or other multimedia content to a large audience.
- Other I/O intensive applications like collaborative platforms.
- Web backends that follow microservices architecture.
However, Node.js’ unique qualities make it not an ideal choice for some other types of applications. Applications that carry out CPU-intensive tasks like complex mathematical computations do not bode well with Node.js because of its single-threaded execution.
Advance Node JS Interview Question
What are the main advantages of using Node.js?
Some of the main advantages of using Node.js are as follows:
- Productivity: Since Node.js is based on JavaScript, we can use same language for front-end as well as back-end. This increases the productivity of development of an application.
- Fast: Node.js is very fast. It runs on Google’s V8 engine that compiles JavaScript into machine code and makes it run very fast.
- Asynchronous: Since Node.js is event-driven, we can implement asynchronous processing. This helps in handling a large amount of requests in a short period of time.
- Real time applications: With Node.js we can easily build Real-time applications that require real-time interaction and processing. E.g. Gaming or Chat applications.
- Streaming: It is very easy to read/write from we sockets in Node.js. This makes it very suitable for streaming applications.
What are the types of applications that can be built by using Node.js?
Node.js can be used for building a wide-variety of applications.
Some of the main types of applications that can be easily built with Node.js are as follows:
- Real-time web applications: We can use Node.js to build applications for chatting and gaming purpose.
- Web applications: Even we can build web-applications with Node.js.
- Payment applications: We can even use Node.js to build fast payment applications. Even PayPal widely uses Node.js for their system.
- Streaming applications: Node.js provides very good performance for creating and running a streaming application.
Why Node.js is based on single threaded architecture?
Node.js is based on single threaded architecture due to the reason that it runs on Google’s V8 engine which is a single threaded architecture.
Over the time, single threaded architecture of Node.js provides much better performance than one thread per request architecture.
Node JS Interview Question
What are the different types of APIs available in Node.js?
Node.js mainly provides following two types of APIs:
- Synchronous API: These are blocking functions that wait for the response to come back.
- Asynchronous API: These are non-blocking functions that keep on processing in the background.
Can we run Node.js on Windows environment?
Yes, it is possible to run Node.js on Windows environment. We have to download windows .msi file to run Node.js applications on Windows.
What are the disadvantages of Node.js?
Although Node.js is getting popular for certain applications, it has some disadvantages as well. Some of these are as follows:
- Libraries: Node.js does not have a large number of libraries as compared with other frameworks like Spring and languages like Java.
- Callback: For some synchronous applications, event driven callback mechanism is not suitable.
- Documentation: Still it is difficult to find one common place with complete documentation of Node.js.
- Talent: Since Node.js is a new field it is difficult to find and hire talented developers in this area.
Advance Node JS Interview Question
How can we handle blocking I/O operations in Node.js?
In Node.js we can use asynchronous calls to handle blocking I/O operations. In an asynchronous main thread of our program is not waiting for an I/O operation to finish.
Let say we want to get some information from Database, we just fire and event. Our main program keeps executing the steps after that event. In the meantime when we receive output from database read, it emits another event. This event leads to further processing on the data retrieved from the database.
Where as our main program keep on executing all the time.
What is the difference between Node.js and AngularJS?
Both Node.js and AngularJS use JavaScript in the implementation. Due to this, they appear similar in nature. But there are fundamental differences between these two.
AngularJS is a web framework that is implemented in JavaScript. It is used to build front-end web applications with powerful back-end support. In AngularJS we use tags to create single page applications. It is based on Model View Controller (MVC) design pattern.
Node.js is a platform to create server-side software applications. It is based on Google’s V8 Javascript engine. We can use it to create a highly scalable system with large data usage.
What is NPM in Node.js?
NPM or npm is Node Package Manager in Node.js. There are two main uses of NPM:
- Online Repository: It provides Online repository for node.js packages. We can store and search node.js packages in NPM.
- Installation: It also provides a command line utility to install and uninstall node.js packages. We can do version management and dependency management with NPM. We can even update the version of a module with NPM.
Node JS Interview Question
Why Node.js application is scalable?
In a Node.js application we do multiple I/O operations in parallel. Since I/O operations do not share data between threads, we can execute these in parallel. Once I/O is complete, it emits event that can be handled by the Event Loop. Due to handling of multiple I/O in parallel Node.js application can be scaled easily.
Scalability in Node.js is more applicable to web-services where we have a large amount of I/O operations.
One limitation of Node.js scalability is that we cannot use it for an application with parallel processes that share data.
What is a Child Process in Node.js?
There is a child_process module in Node.js that can be used to spawn child processes.
We can use commands like spawn(), exec(), fork() etc to create new Child Processes.
These child processes can be synchronous as well as asynchronous.
For shell script automation, synchronous child process can be used. In asynchronous mode, we can specify a callback that will be called when Child process terminates.
How will you convert a Buffer to JSON in Node.js?
Node.js provides utility method buffer.toJson() to convert a buffer data into JSON format. We can use it to convert Buffer contents to JSON format.
Advance Node JS Interview Question
Why do we use __filename in Node.js?
In Node.js __filename is the name of the current module. It is the absolute path of the current module file.
As per documentation, the __filename is not necessarily the same as the file name used in the command line for a main program in Node.js.
In general, __filename is local to a module.
What is the use of Timers is Node.js?
Node.js provides a useful module timers (aka Timers) to schedule functions at a later point of time.
Timer functions are global. Therefore there is no need to call require(‘timers’).
These API are similar to the APIs in web browser for timers tasks.
What are the important APIs in Timers module in Node.js?
Some of the important APIs in Timers module of Node.js are as follows:
- Immediate: We can use set Immediate() to call a function immediately. We can use clear Immediate() to cancel the scheduled action.
- Timeout: This set Timeout() API is used to set timeout for event loop to not exit the program till the timeout period is over. Once timeout period is over, Event Loop will exit.
- Interval: We use set Interval() to call the function when the time interval elapses.
- Clear: All the above three APIs provide clear APIs to clear any Immediate, Timeout or Interval settings.
Node JS Interview Question
What is the use of net.Socket in Node.js?
Node.js provides net.Socket class in net module that can be used for creating a new socket object.
Socket is an abstraction of TCP socket. In this implementation we can use it as a duplex stream.
A client can create net.Socket and use it to connect to a server. Node.js can also create net.Socket and pass it in a connection to client.
We have to set readable and writable flags to allow reads and writes on this socket.
What are the important events of net.Socket in Node.js?
Some of the important events of net.Socket in Node.js are as follows:
- Connect: This event is emitted when a connection is successfully established.
- Lookup: This event is emitted after resolving the hostname but before the connection is established.
- Close: When server closes, this event is emitted.
- End: When socket sends FIN packet, this event is emitted.
- Data: This event is emitted when data is received.
- Drain: This event is emitted when the write buffer becomes empty.
- Timeout: This event emits when socket timeouts due to inactivity.
- Error: This is an event that emits on occurrence of an error.
Can we build a REST service in Node.js?
Yes, we can build a REST (Representational State Transfer) service in Node.js.
We can use Express JS framework for this purpose.
We can provide implementation for GET, POST and PUT requests to handle REST services on a resource.
A simple implementation with express is as follows:
var express = require(‘express’);
var app = express();
app.get(‘/’, function(req, res){
res.send(‘hello Node!’);
});
app.listen(3000);
Advance Node JS Interview Question