Express and Node JS Interview Questions & Answers

node-js-interview-questions-annswers

1. What is node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment built on Chrome’s V8 JavaScript engine. It allows developers to execute JavaScript code outside of a web browser, making it possible to run server-side applications using JavaScript.

Node.js is event-driven and non-blocking, which means it can efficiently handle a large number of concurrent connections without consuming excessive system resources. This is achieved through its asynchronous, event-driven architecture, which allows tasks to be executed concurrently without waiting for previous operations to complete.

This enables developers to write server-side code using the same language and tools as they use for front-end development, fostering a more cohesive development environment.


2. How node.js works?

Node.js operates within a V8 environment, utilizing JavaScript as its scripting language. By employing non-blocking I/O and a single-threaded event loop, it achieves exceptional performance and throughput.


3. Explain Modules in Node Js ?

In Node.js, modules are a fundamental concept used to organize and encapsulate code into reusable units. Modules are essentially JavaScript files that contain functions, objects, or variables that can be imported and used in other parts of the application. This modularity allows developers to break down their code into smaller, more manageable pieces, promoting code reusability, maintainability, and better organization.


4. What do you mean by the term I/O ?

In the context of computing, I/O stands for Input/Output. It refers to the communication between a computer system (such as a server, desktop computer, or smartphone) and external devices or processes. Input refers to data or information that is received by the computer system, while output refers to data or information that is sent out or produced by the computer system.

I/O operations can be classified into two categories:

  1. Blocking I/O: In this type of I/O, the program waits for the I/O operation to complete before moving on to the next task. During this waiting time, the program remains idle, which can be inefficient when dealing with multiple concurrent operations.

  2. Non-blocking I/O: In non-blocking I/O, the program can initiate an I/O operation and continue with other tasks without waiting for the operation to complete. The program is notified when the I/O operation finishes, and it can then handle the result. This approach allows the program to make better use of its resources, as it can handle multiple I/O operations simultaneously without being blocked.

In the context of Node.js, its non-blocking I/O model allows it to efficiently handle multiple concurrent connections and I/O operations, making it well-suited for building scalable and high-performance applications, such as web servers and real-time applications.


5. Is Node Js Single-threaded ?

Yes, Node.js is primarily single-threaded. However, it is essential to understand that Node.js employs a non-blocking I/O and an event-driven architecture, which allows it to handle asynchronous operations efficiently and concurrently.


6. What does event-driven programming mean?

Event-driven programming is a programming paradigm in which the flow of the program is determined by events that occur within the system or application, rather than being dictated by a predefined sequence of instructions.

In event-driven programming, the program continuously listens for events, such as user actions, sensor inputs, system events, or messages from other components, and responds to them by executing specific event handlers or callbacks.


7. For what require() is used in Node Js ?

In Node.js, the require() function is used to include modules (i.e., JavaScript files) and their functionalities into your current file, making them accessible for use within that file. This allows you to organize your code into separate modules, promoting code reusability and maintainability.

When you use require() in Node.js, it essentially loads the specified module and returns the module’s exports object. The exports object contains the functions, objects, or variables that you want to make available to other parts of your application.


 8. Where can we use node.js?

Node.js is a versatile runtime environment and can be used in various scenarios and types of applications. Some of the common use cases for Node.js include:

  1. Web Servers and APIs

  2. Real-time Applications

  3. Microservices

  4. Command-line Tools

  5. Streaming Services

  6. Internet of Things (IoT)

  7. Data-intensive Applications

  8. Serverless Functions

  9. Desktop Applications


9. In which Language Node Js is written ?

Node js is written in C, C++, JavaScript. It utilizes the open source V8 Javascript Engine from Google to convert Javascript code to C++.


 10. Advantage of node.js?

The advantages of using Node.js include:

  1. High Performance

  2. Scalability

  3. Real-time Capabilities

  4. Code Reusability

  5. Vast Ecosystem

  6. JavaScript Everywhere

  7. Easy to Learn

  8. Quick Prototyping

  9. Support for Asynchronous Programming

  10. Cross-platform Compatibility


11. List the types of applications you can build using Node Js?

Using Node Js you can build applications like:

  • Internet of Things
  • Real-Time Chats Applications
  • Complex Single-Page Applications
  • Real-Time Collaboration Tools
  • Streaming apps
  • Microservices / API’s

12. How Node js read the content of a file?

Normally NodeJs reads the contents of file in non-blocking, asynchronous manner. Node Js utilizes its key fs API to handle files. The easiest way to read file’s entire content in nodeJs is by using the fs.readFile technique. Below is sample software for asynchronous and synchronous reading of file in NodeJs.

Reading a file in node asynchronously/ non-blocking

Reading a file in node asynchronously/blocking


 

13. What are the two types of API functions in Node.js ?

In Node.js, there are primarily two types of API functions:

a)    Asynchronous (Non-Blocking) API Functions

b)    Synchronous (Blocking) API Functions


14. What are Streams? List types of streams available in Node Js ?

Streams are special types of objects in Node that allow us to read data from a source or write data to a destination continuously. There are 4 types of streams available in Node Js, they are

  • Readable − For reading operation.
  • Writable − For writing operation.
  • Duplex − Used for both read and write operation.
  • Transform − A type of duplex stream where the output is computed based on the input.

15. What is control flow function?

In Node.js and other programming environments, a control flow function is a function that is used to manage the flow of program execution by coordinating and controlling the order in which different tasks or operations are executed. Control flow functions help developers handle asynchronous operations, manage errors, and sequence tasks in a more organized and predictable manner.


16. What’s the first argument passed to a Node Js callback handler?

In Node Js all core modules, as well as most of the community-published modules, follows a pattern where the first argument to any callback handler is an error object. this object is optional, if there is no error then in that case null or undefined is passed to the callback.

Example of the callback function


17. Explain the difference between readFile and createReadStream in Node js ?

  • readFile load the whole file which you had marked to read whereas createReadStream reads the complete file in the parts of the size you have declared.
  • The client will receive the data faster in the case of createReadStream in contrast with readFile.
  • In readFile, a file will first completely read by memory and then transfers to a client but in later option, a file will be read by memory in a part which is sent to clients and the process continue until all the parts finish.

18. Explain the steps how “Control Flow” controls the functions calls?

a). Function Definitions

b)  Control Flow Mechanism

c)  Sequencing Tasks

d)  Parallel Execution

e)  Error Handling


19. Why Node.js is single threaded?

There are several reasons why Node.js was designed to be single-threaded:

  1. Asynchronous I/O: Node.js was built to handle I/O-intensive tasks, such as reading from files, making network requests, and interacting with databases. By using an event-driven, non-blocking architecture, Node.js can efficiently manage these I/O operations without creating additional threads, which can be resource-intensive.

  2. Scalability: The single-threaded nature of Node.js simplifies the management of concurrent connections and allows it to efficiently handle a large number of connections with low overhead. This scalability is particularly important for applications that need to support thousands of concurrent users.

  3. Avoiding Thread Management Overhead: In traditional multi-threaded environments, managing multiple threads can introduce complexity, synchronization issues, and overhead. By using a single-threaded model, Node.js avoids these complexities and streamlines development.

  4. Simplified Programming Model: The single-threaded nature of Node.js, combined with its event-driven architecture, leads to a simpler and more intuitive programming model for developers. It allows developers to reason about the flow of the program more easily, as there are no concerns about thread synchronization or race conditions.

  5. Focusing on Asynchronous Paradigm: By being single-threaded, Node.js encourages developers to embrace asynchronous programming patterns, such as callbacks, Promises, and Async/Await. This approach is well-suited for I/O-bound operations and promotes more efficient use of system resources.

While Node.js itself operates on a single thread for executing JavaScript code, it can still leverage multiple threads indirectly through mechanisms like Worker Threads for certain CPU-intensive tasks. However, these additional threads are managed separately from the main event loop, and the core execution of Node.js remains single-threaded.

The single-threaded nature of Node.js does come with some limitations. For CPU-intensive tasks that can’t be efficiently parallelized, it may not be the best choice. However, in many cases, Node.js’s single-threaded architecture provides significant advantages in terms of performance, responsiveness, and scalability for applications that primarily deal with I/O operations.


20. What is JIT and how is it related to Node JS ?

JIT stands for Just-in-time. A JIT compiler is a program which is used to send bytecode (it consists of instruction that can be interpreted) to the processor by converting it into instruction. After you have done with writing a program, the compiler compiles the source language statements into bytecode instead of compiling it into the code that carries the information which is similar to the specific hardware platform’s processor.

Relation of JIT with Node: Virtual machine of Nodejs has JIT compilation which improves the execution speed of the code. The virtual machine takes the source code and converts to machine code in runtime. By this, the hot functions which are called very often are compiled to machine code and, hence increasing speed.


21. what is Closures?

A Closure is a function defined within another scope that has access to all the variables within the outer scope. Global variables can be made local (private) with closures.


 22. Can we access DOM in node?

No, we cannot access the DOM (Document Object Model) in Node.js by default.


 23. What factors contribute to the increasing interest of JAVA programmers in Node.js?

Several factors contribute to the increasing interest of JAVA programmers in Node.js:

  1. Asynchronous Programming: Node.js’s event-driven, non-blocking architecture allows JAVA programmers to work with asynchronous programming paradigms similar to those in JAVA, making it easier for them to handle concurrent tasks and I/O operations efficiently.

  2. Simplified Web Development: Node.js streamlines web development by using JavaScript both on the client (with frontend frameworks like React and Angular) and the server (with Node.js). This unification reduces context switching for JAVA programmers and enables them to work across the full stack.

  3. Performance and Scalability: Node.js’s single-threaded, non-blocking I/O model enables excellent performance and scalability, appealing to JAVA developers who need to build highly responsive and scalable applications.

  4. NPM Ecosystem: Node Package Manager (NPM) provides a vast ecosystem of open-source libraries and packages. JAVA programmers can leverage these modules to accelerate development and solve common challenges without reinventing the wheel.

  5. Real-time Capabilities: Node.js is well-suited for real-time applications, such as chat apps and gaming servers, due to its ability to handle simultaneous connections and process real-time data efficiently.

  6. Lightweight and Fast: Compared to JAVA, Node.js has a smaller footprint and faster startup times, making it a compelling choice for certain projects where lightweight and rapid development are prioritized.

  7. Community and Support: Node.js has a large and active community, leading to extensive documentation, tutorials, and resources that JAVA programmers can rely on to learn and excel in the Node.js ecosystem.

  8. Microservices Architecture: Node.js is well-suited for building microservices due to its modular and lightweight nature. This appeals to JAVA programmers involved in building distributed and scalable systems.

  9. Serverless Architectures: Node.js is widely used in serverless computing environments like AWS Lambda. JAVA programmers can leverage this to develop serverless functions and applications with ease.

  10. Innovation and Job Opportunities: As Node.js continues to gain popularity, many companies are adopting it for their projects. JAVA programmers with Node.js skills can explore new job opportunities and stay relevant in the ever-evolving tech industry.

The combination of these factors makes Node.js an attractive choice for JAVA programmers, offering them new possibilities and opportunities in the world of web development and server-side programming.


24. What does the term ‘event loop’ refer to in Node.js??

In Node.js, the term “event loop” refers to a fundamental mechanism that allows the runtime environment to handle asynchronous operations efficiently. It is a crucial part of Node.js’s architecture and enables it to manage multiple I/O tasks and event-driven operations concurrently without getting blocked.


25. How to use aggregation in Mongoose?

Aggregations are a set of functions that are used to manipulate the data that has been returned from a MongoDB query. In Mongoose, aggregations work as a pipeline. The aggregate function accepts the array of data transformations which are applied by data using different methods in terms of arguments.

Syntax: db.customers.aggregate([ … aggregation steps go here …]);

In above, aggregation is applied to data of customers.


26. What are the advantage and disadvantages of Node.js?

Advantage:

  1. High Performance: Node.js’s event-driven, non-blocking I/O model allows it to handle a large number of concurrent connections efficiently, resulting in high performance and responsiveness.

  2. Scalability: Due to its non-blocking architecture, Node.js can handle a high number of concurrent users and connections with relatively low resource consumption, making it scalable for applications with rapidly growing user bases.

  3. Asynchronous Programming: Node.js encourages asynchronous programming patterns, making it well-suited for I/O-bound operations and avoiding thread-blocking bottlenecks. This promotes efficient utilization of system resources.

  4. Unified Language: Node.js uses JavaScript both on the client (with frontend frameworks) and the server, which facilitates code sharing and knowledge transfer between front-end and back-end developers.

  5. Vast Ecosystem: Node.js benefits from a large and active community, leading to a rich ecosystem of open-source libraries and packages available through NPM, enabling developers to accelerate development and solve common challenges effectively.

  6. Quick Prototyping: Node.js allows for rapid prototyping and development of applications, reducing time to market and supporting an iterative development process.

  7. Real-time Capabilities: Node.js is well-suited for building real-time applications, such as chat apps and gaming servers, where handling multiple simultaneous connections and real-time data is essential.

Disadvantages:

  1. Single-Threaded: Node.js’s single-threaded nature means it may not be the best fit for CPU-intensive tasks that require parallel processing. CPU-bound operations may block the event loop and reduce application responsiveness.

  2. Callback Hell: Working with deeply nested callbacks can lead to callback hell, making the code difficult to read and maintain. However, modern JavaScript features like Promises and Async/Await mitigate this issue.

  3. Inconsistent APIs: Node.js’s fast-evolving ecosystem may lead to inconsistencies in third-party libraries and APIs, requiring careful selection and attention to version compatibility.

  4. Limited Native Support: Node.js does not have native support for CPU-intensive tasks like image processing or heavy computations, which may require additional solutions or libraries.

  5. Immature Tools: Some tools and libraries in the Node.js ecosystem may still be relatively immature compared to more established technologies like Java.

  6. Learning Curve: Developers coming from other backgrounds may need time to adjust to Node.js’s asynchronous programming and event-driven approach.


27. What is difference between put and patch?

Put:

  • The embedded entity is believed to the modified version of the resources that are deposited on the original server. It is requested to the client to replace the stored is substituted.
  • At the time of updating the resource, you need to forward full payload as the request.

Patch:

  • In this, the information regarding the way of modifying the original server which has the resources to produce a new version is found.
  • At the time of updating the resource, you only need to send the parameter of the resource which you want to update.

28. What are LTS releases of Node.js?

LTS stands Long Term Support version of Node.js that receives all the critical bug fixes along with security updates and performance improvements. These versions are supported for at least 18 months and mainly focus on stability and security. The modifications done to the LTS versions are restricted to the bug fixes, security upgrade, npm, and documentation updates, performance improvement, etc.


29. List of Http requests type?

Http defines a set of request methods to perform the desired actions. These request methods are:

  1. GET: The GET method asked for the representation of the specifies resource. This request used to retrieve the data.
  2. POST: The POST technique is utilized to present an element to the predetermined resource, generally causing a change in state or reactions on the server.
  3. HEAD: The HEAD method is similar to the GET method but asks for the response without the response body.
  4. PUT: This method is used to substitute all current representations with the payload.
  5. DELETE: It is used to delete the predetermined resource.
  6. CONNECT: This request is used to settle the TCP/IP tunnel to the server by the target resource
  7. OPTION: This method is used to give back the HTTP strategies to communicate with the target resource.
  8. TRACE: This method echoes the message which tells the customer how much progressions have been made by an intermediate server.
  9. PATCH: The PATCH method gives partial modifications to a resource.

30. What are CommonJs Modules ?

CommonJS Modules is the Standard how to code modules are structured. It specifies an ecosystem for JavaScript outside on the server or for native desktop applications.


31. How can models be defined in Express JS?

There is no notion of any database in Express JS. So, the concept of models is left up to third-party node modules, allowing the users to interface with nearly any type of database.


32. How to config properties in Express JS?

In Express JS, there are two ways for configuring the properties:

  • With process.ENV:
  • A file with the name “.env” is to be created inside the project folder.
  • All the properties are to be added in the “.env” file.
  • Any of the properties can be used in server.js.
  • With require JS:
  • A file with the name “config.json” is to be created in the config folder inside the project folder.
  • The config properties are to be added in the config.json file.
  • Now, require should be used to access the config.json file.

33. How to authenticate users in express JS?

Since authentication is an opinionated area which is not ventured by express JS, therefore any authentication scheme can be used in express JS for the authentication of users.


34. What function are arguments available to Express JS route handlers?

The arguments which are available to an Express JS route handler-function are-

  • Req – the request object
  • Res – the response object
  • Next (optional) – a function which is used to pass control to one of the subsequent route handlers.

The third argument is optional and may be omitted, but in some cases, it is useful where there is a chain of handlers and control can be passed to one of the subsequent route handlers skipping the current one.


35. List of web applications which can be built using Express JS?

Single-page, multi-page, and hybrid web applications can be built using Express JS.


36. How can plain HTML be rendered in express JS?

There’s no need to render HTML with the res.render () function. If there’s a specific file, then you should use the res.sendFile () function. If any assets are being served from a dictionary, then express.static () middleware function needs to be used.


37. What is the use of Express JS?

Express.js is a lightweight web application which helps in organizing the web application into MVC architecture on the server side.


38. Why to use Express.js?

Below are the few reasons why to use Express with Node.js

  • Express js is built on top of Node.js. It is the perfect framework for ultra-fast Input / Output.
  • Cross Platform
  • Support MVC Design pattern
  • Support of NoSQL databases out of the box.
  • Multiple templating engine support i.e. Jade or EJS which reduces the amount of HTML code you have to write for a page.
  • Support Middleware, basic web-server creation, and easy routing tools.

39. Write the steps for setting up an Express JS application.

Following are the steps used to set up an express JS application: –

  1. A folder with the same name as the project name is created.
  2. A file named package.json is created inside the folder created.
  3. “npm install” command is run on the command prompt. It installs all the libraries present in package.json.
  4. A file named server.js is created.
  5. “Router” file is created inside the package which consists of a folder named index.js.
  6. “App” is created inside the package which has the index.html file.

This way, an express JS application is set up.


40. List some features of Express JS.

Some of the main features of Express JS are listed below: –

  • It is used for setting up middlewares 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.

41. List out some new features introduced in ES6?

Following are the list of few new Features introduced in ES6

  • const and let keywords
  • Array helper functions like map, forEach, filter, find, every, some, reduce
  • Arrow functions
  • Classes and enhanced object literals
  • Template strings
  • Default function arguments
  • Rest and spread operators
  • Promises
  • Modules
  • Multi-line Strings
  • Destructuring Assignment

42. Write a simple code to enable CORS in Node js?

CORS stands for Cross-Origin Resource Sharing. It a is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.

Use below code to enable CORS on NodeJS


43. What do you mean by Express JS?

Express JS is an application framework which is light-weighted node JS. A number of flexible, useful and important features are provided by this JavaScript framework for the development of mobile as well as web applications with the help of node JS.


44. Explain ECMAScript ?

ECMAScript is the standard on which Javascript is based on. It was created to standardize Javascript. It is commonly used for client-side scripting on the World Wide Web and used by Node Js for writing server applications and services.


45. How can you check the installed version of Node Js ?

Use node -v command to check the installed version of Node Js


46. Explain What is NPM ?

NPM stands for node package manager. It is default Package Manager for JavaScript programming language. NPM is used for installing/updating packages and modules of Javascript.


47. Explain module.exports in Node Js ?

The method or variable defined in modules cannot be directly accessible by the outer world, that means you cannot call a module member from the external file. In order to access module member, we need to export the functions or variables of modules using module.exports method.

Syntax and usage:


48. What is the difference between Node.js vs Ajax?

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.


49. What are the Challenges with Node.js ?

Emphasizing on the technical side, it’s a bit of challenge in Node.js to have one process with one thread to scale up on multi core server.


50. What is ‘Callback’ in node.js?

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.


Note:-  Question Answer based on career.guru99.com and onlineinterviewquestions.com

Related posts