KEMBAR78
Node JS Interview Q & A | PDF | World Wide Web | Internet & Web
0% found this document useful (0 votes)
5 views9 pages

Node JS Interview Q & A

Uploaded by

vojeley878
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Node JS Interview Q & A

Uploaded by

vojeley878
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Node JS Interview Q & A

1. What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment. It allows you to run


JavaScript code on the server-side, outside of a web browser. Node.js uses the V8 JavaScript engine (the
same engine used by Google Chrome) to execute code.Node.js is designed to be asynchronous and non-
blocking. This means it can handle multiple operations at the same time without waiting for one to finish
before starting another. This is achieved through event-driven architecture.

2. What is npm?

npm stands for Node Package Manager. It is a package manager for JavaScript and is the default
package manager for Node.js. npm allows you to install, share, and manage code packages written in
JavaScript. These packages can be libraries, tools, or frameworks that you can use in your Node.js
projects.

3. What is REP in Node.js?

REPL stands for Read-Eval-Print Loop. It's an interactive shell that allows you to execute JavaScript
code one line at a time.For start the REPL open your terminal. Type node and press Enter. You should
see a prompt (>) where you can start typing JavaScript code.

4. What is Modules in Node.js?

Modules are reusable pieces of code that you can use to organize your Node.js applications. They help
you break down your application into smaller, manageable parts, making your code more modular,
maintainable, and reusable.In Node.js,

there are three types of modules:

• Core (built-in) modules,

• Local (custom) modules,

• Third-party modules.
5. What is Buffers in Node.js?

A buffer is a temporary storage area for binary data. In Node.js, the Buffer class is a global type for
dealing with binary data directly.

Buffers are like arrays of integers but correspond to raw memory allocations outside the V8 heap. Each
element in a buffer is an 8-bit integer. Buffers are used to handle raw binary data that might come from
a file, network, or other streams.

6. 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

7. Why is Node.js Single-threaded?

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

8. 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.

9. What are the pros and cons of Node.js?

# Node.js Pros:

• Fast processing and an event-based model

• Uses JavaScript, which is well-known amongst developers

• Node Package Manager has over 50,000 packages that provide the functionality to an
application
• Best suited for streaming huge amounts of data and I/O intensive operations

# Node.js Cons:

• Not suitable for heavy computational tasks

• Using callback is complex since you end up with several nested callbacks

• Dealing with relational databases is not a good option for Node.js

• Since Node.js is single-threaded, CPU intensive tasks are not its strong suit

10. 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.

11. 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

12. What kind of API function is supported by Node.js?

There are two types of API functions supported by Node.js:

• Synchronous: These API functions are used for blocking code.

• Asynchronous: These API functions are used for non-blocking code.

13. What is middleware?

Middleware is the function that works between the request and the response cycle. Middleware gets
executed after the server receives the request and before the controller sends the response.
14. What are promises in Node.js?

A promise is basically an advancement of callbacks in NodeJS. In other words, a promise is a JavaScript


object which is used to handle all the asynchronous data operations. While developing an application
you may encounter that you are using a lot of nested callback functions which causes a problem of
callback hell. Promises solve this problem of callback hell.

15. What is callback hell?

Callback hell is an issue caused due to a nested callback. This causes the code to look like a pyramid
and makes it unable to read To overcome this situation we use promises.

16. 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

17. What are streams in Node.js?

Streams are methods used to handle reading/writing files, network communication, or end-to-end
information exchange. These methods are used to process large data by reading data piece by piece,
process its content, especially for data files larger than free memory space.

Streams help to read and write data as:

• Readable: Data can be read from the stream using fs.createReadStream() command.

• Writable: Data can be written into the stream using fs.createWriteStream() command.

• Duplex: Readable and writable streams are duplex and use net.Socket command.
• Transform: Duplex streams converting read and written data as zlib.createDeflate().

18. Difference between package.json and package.lock.json files?

In a Node.js project, the package.json file is mandatory, while the package-lock.json file is not
mandatory but highly recommended for projects using npm for package management.

package.json is a manifest file that contains metadata about the project and specifies its
dependencies. It defines the project configuration. It includes details such as the project name, version,
entry point, script commands, and most importantly, the list of dependencies and their versions.

package.lock.json is automatically generated by npm, when dependencies are installed or updated. It


contains a detailed record of the exact versions of all dependencies that were installed for the project at
a specific point in time. this file is crucial for enabling reproducible and consistent builds in a project.

19. What is Blocking?

It refers to the blocking of further operation until the current operation finishes. Blocking methods are
executed synchronously. Synchronously means that the program is executed line by line. The program
waits until the called function or the operation returns.

20. What is Non-Blocking ?

It refers to the program that does not block the execution of further operations. Non-Blocking
methods are executed asynchronously. Asynchronously means that the program may not necessarily
execute line by line. The program calls the function and move to the next operation and does not wait
for it to return.

21. What is the control flow function?

Control flow functions are used to dictate the order in which specific code blocks or functions are
executed. These functions are used to manage the flow of execution within a program, enabling
developers to handle asynchronous operations, iterate through collections, handle conditional logic, and
more.

22. What is a Web Socket?

WebSocket is a communication protocol enabling full-duplex communication, allowing simultaneous


two-way communication between a user’s browser and the server. It establishes a continuous
connection, enabling messages to be sent between the web server and browser at any time. Unlike
traditional request/response formats, WebSocket facilitates server-initiated communication with the
client. To implement WebSocket in NodeJS, the “socket.io” dependency needs installation. Additionally,
installing the “express” module is essential for server-side applications.

23. What is CORS?

CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented in web browsers
to restrict web pages from making requests to a different domain than the one that served the web
page.

CORS is a security feature that regulates cross-origin requests, allowing secure communication
between different domains while protecting users’ data from unauthorized access and potential security
threats.

24. Difference between dependency and dev-dependency?

Dependencies are the packages that are required for the application to run in the production
environment.

DevDependencies are the packages that are only needed for development and testing purposes.
These packages include tools, libraries, and utilities that are used during the development, testing, and
build process, but are not required for the application to function in the production environment.

25. Difference between Authentication and Authorization?

Authentication is the process of validating the identity of a user or entity, through the credentials,
such as usernames, passwords, biometric data, or security tokens.

Authorization is the process of determining the rights and privileges of a user to access the resources.
Authorization typically involves specifying what resources or operations a user can interact with based
on their role, group membership, or other relevant attributes.

26. How to handle errors in node?

In Node.js, errors can be handled using a variety of techniques, including try…catch blocks, error-first
callbacks, and the use of error event emitters.
27. What are the different phases of the event loop?

The Event Loop is composed of the following six phases, which are repeated for as long as the
application still has code that needs to be executed:

1. Timers

2. I/O Callbacks

3. Waiting / Preparation

4. I/O Polling

5. setImmediate() callbacks

6. Close events

The Event Loop starts at the moment Node.js begins to execute your index.js file, or any other
application entry point.

These six phases create one cycle, or loop, which is known as a tick. A Node.js process exits when
there is no more pending work in the Event Loop, or when process.exit() is called manually.

Some phases are executed by the Event Loop itself, but for some of them the main tasks are passed to
the asynchronous C++ APIs.

Phase 1: timers: The timers phase is executed directly by the Event Loop. At the beginning of this
phase, the Event Loop updates its own time. Then it checks a queue, or pool, of timers. This queue
consists of all timers that are currently set. The Event Loop takes the timer with the shortest wait time
and compares it with the Event Loop’s current time. If the wait time has elapsed, then the timer’s
callback is queued to be called once the call stack is empty.

Phase 2: I/O callbacks: This is a phase of non-blocking input/output. The asynchronous I/O request is
recorded into the queue and then the main call stack can continue working as expected. In the second
phase of the Event Loop the I/O callbacks of completed or errored out I/O operations are processed.

Phase 3: idle / waiting / preparation: This is a housekeeping phase. During this phase, the Event Loop
performs internal operations of any callbacks. It is primarily used for gathering information, and
planning of what needs to be executed during the next tick of the Event Loop.
Phase 4: I/O polling (poll phase): This is the phase in which all the JavaScript code that we write is
executed, starting at the beginning of the file, and working down. Depending on the code it may execute
immediately, or it may add something to the queue to be executed during a future tick of the Event
Loop.

During this phase, the Event Loop is managing the I/O workload, calling the functions in the queue
until the queue is empty, and calculating how long it should wait until moving to the next phase. All
callbacks in this phase are called synchronously in the order that they were added to the queue, from
oldest to newest.

Note: this phase is optional. It may not happen on every tick, depending on the state of your
application.

If there are any setImmediate() timers scheduled, Node.js will skip this phase during the current tick
and move to the setImmediate() phase.

Phase 5: setImmediate() callbacks: Node.js has a special timer, setImmediate(), and its callbacks are
executed during this phase. This phase runs as soon as the poll phase becomes idle. If setImmediate() is
scheduled within the I/O cycle it will always be executed before other timers regardless of how many
timers are present.

Phase 6: close events: This phase executes the callbacks of all close events. For example, a close event
of web socket callback, or when process.exit() is called. This is when the Event Loop is wrapping up one
cycle and is ready to move to the next one. It is primarily used to clean the state of the application.

28. If Node.js is single-threaded, then how does it handle concurrency?

The Multi-Threaded Request/Response Stateless Model is not followed by the Node JS Platform, and
it adheres to the Single-Threaded Event Loop Model. The Node JS Processing paradigm is heavily
influenced by the JavaScript Event-based model and the JavaScript callback system. As a result, Node.js
can easily manage more concurrent client requests. The event loop is the processing model's beating
heart in Node.js.
29. What Is the Node.js fs (File System) Module?

The built-in Node.js file system module helps us store, access, and manage data on our operating
system. Commonly used features of the fs module include fs.readFile to read data from a file,
fs.writeFile to write data to a file and replace the file if it already exists, fs.watchFile to get notified of
changes, and fs.appendFile to append data to a file. The fs core module is available in every Node.js
project without having to install it.

30. 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.

You might also like