Node.js Interview Questions | Basic
- Mozilla FireFox - SpiderMonkey
- Microsoft Edge - Chakra
It's very easy to Install Node.js on Windows, Linux, etc
Node.js has many features which makes node.js more powerful.
- Asynchronous and Event Driven
- It's very fast
- Single Threaded & Highly Scalable
- NPM (Node Package Manager)
- No Buffering
Let's see all above node.js feature details
Asynchronous and Event Driven:
All APIs of Node.js library are asynchronous, that is, non-blocking I/O.
Node.js can handle multiple concurrent request, it's the power of node.js. After it finish executing request it will run a callback to notify about its completion.
It's very fast:
Single Threaded & Highly Scalable:
Node.js is a single threaded, which in background (Under the hood Node.js uses many threads through libuv) uses multiple threads to execute asynchronous code.
Node.js applications uses Single Threaded Event Loop Model to handle multiple concurrent requests.
The Event Loop mechanism helps the server to respond in a non-blocking way, resulting in making the server highly scalable as opposed to traditional servers which create limited threads to handle requests.
NPM (Node Package Manager):
NPM stands for Node Package Manager, it allows us to install various Packages for Node.js Application.
Node.js applications never buffer any data. They simply output the data in chunks.
Node.js has a very good community which always keeps the framework updated with the latest trends in the web development.
Nodemon is a tool which monitor node.js applications for any changes in your source code and it automatically restart your server.
- Nodemon is the best tool for development,while developing node.js project.
- Nodemon is available as NPM Package.
- You can also install nodemon as a development dependency:
REPL allows for the easy creation of CLI (Command Line Interface) applications.
- The REPL stands for "Read Eval Print Loop". It is a simple program that accepts the commands, evaluates them, and finally prints the results.
- REPL provides an environment similar to that of Unix/Linux shell or a window console, in which we can enter the command and the system, in turn, responds with the output.
- To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node. It will change the prompt to > in Windows and MAC.
EVAL: It Executes the data structure.
PRINT: It Prints the result obtained after evaluating the command.
LOOP: It repeat the above command until the user presses Ctrl+C two times.
There are mainly 2 ways
- using process.exit()
- Press Ctrl + C twice, or type .exit and press Enter
Node.js Interview Questions | Intermediate
- LTS: stands for Long Term Support. LTS releases receives all the critical bug fixes, security updates and performance improvements.
- LTS version have community support and maintenance for at least 18 months, therfore it is good to use Active LTS or Maintenance LTS releases in Production.
- Importance of LTS Version: Once a Current release line becomes LTS, no new features or breaking changes will be added to that release.
LTS:- Long Term Support (LTS) version has at least 18 months support and maintenance, so it's more stable and secure.
Stable:- Current Stable version has 8 months support and maintenance.
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources to be requested from another domain/server.
- res.header() OR res.set()
- express cors module
If you are using express.js you can use cors module
Both two methods do exactly the same thing, set the headers HTTP response.
|It is a native method of node.js||It is an alias of res.set() method from express framework|
|It allows you to set only a single header||It allows you to set multiple headers|
You may also like - MongoDB Interview Questions Answers
A callback is a function, which is called automatically at the completion of a given task. Node makes heavy use of callbacks.
Callback hell refers to a coding pattern where there is a lot of nesting of callback functions. The code forms a pyramid-like structure and it becomes difficult to debug.
It is also called - pyramid of doom
Just imagine if you need to make callback after callback:
- The first argument of the callback is reserved for an error object. If an error occurred, it will be returned by the first err argument.
- The second argument of the callback is reserved for any successful response data. If no error occurred, err will be set to null and data will be returned in the second argument.
Use process 'uncaughtException' and 'unhandledRejection' events
NPM stands for Node Package Manager, it comes with node.js & allows us to install various packages for Node.js Applications.
Note: As of npm 5.0.0 and greater, installed modules are added as a dependency by default, so the --save option is no longer needed.
NVM stands for Node Version Manager
- NVM helps to use and manage multiple versions of node.js.
- You can use nvm to change your node.js versions very easily.
- NVM is very helpful if you are working on multiple projects of Node.js having different versions.
- The package.json is a json file which holds all the metadata information about your node.js Application.
- NPM uses this package.json to manage all modules/packages dependencies for your node.js application.
- It will install all the dependencies to ./node_modules directory.
- The package.json file is normally located at the root directory of your node.js project.
- name - name of the package
- version - version of the package
- author - author of the package
- dependencies - list of dependencies. npm automatically installs all the dependencies mentioned here in the node_module folder of the package.
package.json: The package.json is used for more than dependencies - like defining project properties, description, author & license info etc.
package-lock.json: The package-lock.json is primarily used to lock dependencies to a specific version number.
If package-lock.json exists, it overrules package.json
The version number is in semver syntax - major.minor.patch
If your app's package.json contains:
it means to install version 1.0.2 or the latest patch version such as 1.0.4
If your app's package.json contains:
If you see ^1.0.2 it means to install version 1.0.2 or the latest minor or patch version such as 1.1.0
Node.js Interview Questions | Advanced
If an application has to wait for some I/O operation in order to complete its execution any further than the code responsible for waiting is known as blocking code.
Chaining is a mechanism in node.js to connect the output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.
You may also like - React.js Interview Questions
This is mostly frequently asked Node.js Interview Questions.
Each Node.js modules has it's own context.
Node.js Core Modules comes with its Installation by default. You can use them as per application requirements
First you need to import core module using require() function.
Local modules are user defined modules which are mainly used for specific projects and locally available in separate files or folders within project folders.
First you need to import core module using require() function.
Create a folder common, inside common folder create a new file named utility.js with following code
Now, inside app.js or index.js file import that utility module using require() function.
The 3rd party modules can be downloaded using NPM (Node Package Manager).
There are many ways you can make HTTP requests in Node.js, Few of them are given below, which are mostly used:
- HTTP – the Standard Library
- Request - Deprecated! (Feb 11th 2020)
- Axios - Promise based HTTP client for the browser and node.js
- Debugger: Statement inserting debugger, in the code of java script it will help to enable break point.
- Console: Console module provides debugging feature that is similar in Java script console by browser.
- Streaming: A stream is an abstract interface implemented by various objects in Node.js
- Cluster: It allows us to create child process easily that shares server port.
- DNS: DNS module contains functions.
- Add-ons: It is a dynamically linked shared object.
- Domain: It provides a way to handle multiple different IO operations as a single group.
- Buffer: It is similar to array of integers but corresponds to fixed-sized.
- Global: It is available for all modules.
- Net: It provides asynchronous network wrapper.
- Callbacks: It is called when given task will be completed.
- Error handling: It supports various types of categories error.
- Crypto: It provides cryptographic functionality that includes a set of wrappers for Open SSL’s hash.
- Single Page Applications
- Real-Time services (Chat Applications, Games Servers etc)
- REST APIs and Backend Applications
- Blogs, CMS, Social Applications.
- Data Streaming Applications
- Utilities and Tools
- Advertisement Servers.
In Short, it's good to use Node.js, when you need high levels of concurrency but less amount of dedicated CPU time.
we should not use node.js for cases where the application requires long processing time. So, Node.js is best suited when processing needs less dedicated CPU time.
In Short, it's not good for CPU intensive tasks.
Short Answer - Performace Optimization, Sepeartion between Code & Server related stuff, Easy Testing etc.
Express App is responsible for Code Logics, DB Connections, API Stuff etc. while Server is responsible for network related stuff like port, protocol etc.
So API declaration, Code Logics etc, should reside in app.js and Server network declaration, should reside in /bin/www
Yes, Node.js is Single-threaded
There are mainy two ways to achieve this
- cluster module
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 single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load.
The cluster module allows easy creation of child processes that all share server ports.
Running Node.js will now share port 8000 between the workers:
If you are using PM2 - Process Manager then you can directly use
cluser.fork is implemented on top of child_process.fork. one more thing that cluster.fork brings is, it enables you to listen on a shared port.
The reactor design pattern is an event handling pattern.
It is used for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronously to the associated request handlers.
- libuv is library written in C language to make Node.js compatible with every OS and provide the non-blocking I/O behaviour.
- libuv provides a threadpool (threadpool is global and shared across all event loops.) which can be used to run user code and get notified in the loop thread.
- Its default size is 4, but it can be changed at startup time by setting the UV_THREADPOOL_SIZE environment variable to any value (the absolute maximum is 1024).
process.nextTick() and setImmediate() are used to schedule callbacks in the event loop.
Any function passed as the setImmediate() argument is a callback that’s executed in the next iteration of the event loop.
A function passed to process.nextTick() is going to be executed on the current iteration of the event loop, after the current operation ends.
This object expose two methods
- emit is used to trigger an event.
- on is used to add a callback function which will be executed when the event is triggered.
addListener() is an alias of on() in Node.js
There are too many IDEs some of them which are most popular are listed below.
- MS Visual Studio Code | VS Code
- Sublime Text
You may also like - Top 10 Express.js Interview Questions