Node.JS Interview Questions Part-1

1. What is Node.js?

Solution: Node.js is an open-source, server-side JavaScript runtime environment built on Chrome’s V8 JavaScript engine.

2. What is NPM?

Solution: NPM (Node Package Manager) is a package manager for Node.js that allows developers to install and manage third-party libraries or modules.

3. How do you import external modules in Node.js?

Solution: You can use the required function to import external modules in Node.js. For example, const express = require(‘express’); imports the Express framework.

4. Explain the concept of event-driven programming in Node.js.

Solution: Event-driven programming is a programming paradigm where the flow of the program is determined by events. Node.js uses an event loop to handle events and callbacks.

5. What is the difference between setTimeout and setImmediate?

Solution: setTimeout schedules a function to be executed after a specified delay, while setImmediate schedules a function to be executed in the next iteration of the event loop.

6. How can you handle errors in Node.js?

Solution: Errors in Node.js can be handled using try-catch blocks or by attaching an error event listener to the process object.

7. What is the purpose of the module? Do exports object in Node.js?

Solution: The module. Exports object is used to export functions, objects, or values from a module so that they can be accessed by other modules using require.

8. What is a callback function in Node.js?

Solution: A callback function is a function that is passed as an argument to another function and is invoked when a particular event occurs or when the parent function completes its execution.

9. What is the role of the Buffer class in Node.js?

Solution: The Buffer class is used to handle binary data in Node.js and is useful when working with files, network streams, or other sources of binary data.

10. How do you handle file operations in Node.js?

Solution: Node.js provides the fs module, which allows you to perform file operations such as reading, writing, deleting, and renaming files.

11. Explain the concept of middleware in Node.js.

Solution: Middleware is a function that sits between the client and server in a Node.js application. It can modify the request or response objects, invoke the next middleware function, or terminate the request-response cycle.

12. What is the purpose of the process object in Node.js?

Solution: The process object provides information about the current Node.js process and allows you to control the process’s behaviour. It also provides access to command-line arguments and environment variables.

13. How do you handle concurrent operations in Node.js?

Solution: Node.js provides features such as callbacks, promises, and async/await to handle concurrent operations and avoid blocking the event loop.

14. What is a stream in Node.js?

Solution: A stream is an abstract interface in Node.js used to handle streaming data, allowing data to be read or written in chunks rather than loading the entire data into memory.

15. How do you create a web server in Node.js?

Solution: You can create a web server in Node.js using the built-in http or https module, or by using popular frameworks like Express or Koa.

16. What is the purpose of the __dirname variable in Node.js?

Solution: The __dirname variable stores the absolute path of the directory containing the currently executing script.

17. How can you handle form data in Node.js?

Solution: To handle form data in Node.js, you can use the body-parser middleware or the built-in querystring module to parse the data sent by HTML forms.

18. Explain the concept of clustering in Node.js.

Solution: Clustering in Node.js allows you to create multiple worker processes that share the same server port, enabling better utilization of multi-core systems and improved performance.

19. How do you handle authentication in Node.js?

Solution: Node.js provides various modules and strategies for handling authentication, such as Passport.js, which supports different authentication methods like username/password, OAuth, and JWT.

20. What is the purpose of the child_process module in Node.js?

Solution: The child_process module in Node.js allows you to spawn child processes and execute system commands from within a Node.js application.

21. What is the purpose of the cluster module in Node.js?

Solution: The cluster module in Node.js enables the easy creation of child processes (workers) that can share server ports and distribute the load among multiple cores.

22. How do you perform unit testing in Node.js?

Solution: Node.js provides several testing frameworks, such as Mocha, Jest, and Jasmine, which allow you to write and execute unit tests for your Node.js applications.

23. What is the role of the net module in Node.js?

Solution: The net module in Node.js provides an asynchronous network API for creating servers and clients that communicate over TCP (Transmission Control Protocol).

24. How can you handle query parameters in Node.js?

Solution: Query parameters can be accessed in Node.js using the req.query object when using a framework like Express, or by parsing the URL using the built-in url module.

25. Explain the concept of garbage collection in Node.js.

Solution: Garbage collection in Node.js is the process of automatically freeing up memory by identifying and removing objects that are no longer referenced or in use.

26. How do you work with databases in Node.js?

Solution: Node.js provides various database drivers and ORMs (Object-Relational Mappers) for interacting with databases like MongoDB, MySQL, PostgreSQL, and more.

27. What is the purpose of the os module in Node.js?

Solution: The os module in Node.js provides operating system-related utility functions and information, such as CPU architecture, memory, network interfaces, and more.

28. How do you handle cookies in Node.js?

Solution: In Node.js, you can use the cookie-parser middleware or the built-in http module to handle cookies and their parsing.

29. What is the purpose of the util module in Node.js?

Solution: The util module in Node.js provides various utility functions, including object inspection, error creation, promisification, and more.

30. How do you handle file uploads in Node.js?

Solution: To handle file uploads in Node.js, you can use middleware like Multer or busboy that parses and handle the uploaded files.

31. What is event-driven programming in Node.js?

Solution: Event-driven programming in Node.js is a programming paradigm where the flow of the program is determined by events. It involves registering event handlers that are executed in response to specific events occurring in the application.

32. What is the purpose of the http module in Node.js?

Solution: The http module in Node.js provides functionality to create an HTTP server or make HTTP requests. It allows you to handle incoming HTTP requests and send HTTP responses.

33. How do you handle routing in Node.js?

Solution: Routing in Node.js can be handled using frameworks like Express, where you define routes and associate them with specific request handlers or controller functions.

34. What is the purpose of the path module in Node.js?

Solution: The path module in Node.js provides utility functions for working with file and directory paths. It allows you to manipulate and resolve file paths across different operating systems.

35. How do you handle sessions in Node.js?

Solution: Session management in Node.js can be achieved using middleware like express-session or by implementing your own session handling mechanism using cookies or a database.

36. What are streams in Node.js?Explain different types of streams. 

Solution: Streams in Node.js are objects that facilitate the reading or writing of data. There are four types of streams: Readable, Writable, Duplex (both readable and writable), and Transform (a type of duplex stream that can modify or transform the data while reading or writing).

37. How do you handle cross-origin requests in Node.js?

Solution: Cross-origin requests in Node.js can be handled by setting appropriate headers on the server-side response, such as the Access-Control-Allow-Origin header, to specify which origins are allowed to access the server’s resources.

38. What is the purpose of the crypto module in Node.js?

Solution: The crypto module in Node.js provides cryptographic functionality, including encryption, decryption, hashing, and generating secure random numbers.

39. How do you handle asynchronous operations in Node.js?

Solution: Asynchronous operations in Node.js can be handled using callbacks, promises, or async/await syntax. These mechanisms help avoid blocking the event loop and enable non-blocking I/O operations.

40. What is the purpose of the url module in Node.js?

Solution: The url module in Node.js provides utility functions for URL parsing, formatting, and resolving. It helps in working with URLs and their components.

41. How do you handle authentication and authorization in Node.js?

Solution: Authentication and authorization in Node.js can be handled using middleware like Passport.js, where you authenticate users and authorize access based on roles or permissions.

42. What is the purpose of the cluster module in Node.js?

Solution: The cluster module in Node.js allows you to create a cluster of worker processes to distribute the load across multiple CPU cores, enhancing the application’s performance and scalability.

43. How do you handle WebSocket communication in Node.js?

Solution: WebSocket communication in Node.js can be handled using libraries like Socket.io or the built-in ws module, which enables real-time bidirectional communication between the server and the client.

44. What is the purpose of the zlib module in Node.js?

Solution: The zlib module in Node.js provides compression and decompression functionality, allowing you to work with compressed files or streams using gzip, deflate, or zlib algorithms.

45. How do you handle caching in Node.js?

Solution: Caching in Node.js can be implemented using mechanisms like in-memory caching with objects or libraries like Redis. It helps in storing and retrieving frequently accessed data for improved performance.

46. What is the purpose of the process.argv property in Node.js?

Solution: The process.argv property in Node.js provides access to the command-line arguments passed to the Node.js process. It allows you to access and parse the arguments for configuration or input purposes.

47. How do you handle error handling and logging in Node.js?

Solution: Error handling in Node.js can be done using try-catch blocks or by attaching error event listeners. Logging can be implemented using libraries like Winston or by writing custom logging functions to log errors or application events.

48. What is the purpose of the util.promisify function in Node.js?

Solution: The util.promisify function in Node.js is used to convert callback-based functions into functions that return promises, allowing them to be used with async/await or promise chains.

49. How do you handle file downloads in Node.js?

Solution: File downloads in Node.js can be implemented by setting the appropriate headers in the server’s response, such as Content-Disposition and Content-Type, and then streaming the file to the client.

50. What is the purpose of the os module in Node.js?

Solution: The os module in Node.js provides information about the operating system, including CPU architecture, memory, network interfaces, and other system-related details.

Code-Based Questions: –

1. Write a Node.js function to read the contents of a file and return them as a string.

const fs = require('fs');
 
function readFileContents(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

2. Write a Node.js function to make an HTTP GET request to a specified URL and return the response body as a string.

const http = require('http');
 
function makeGetRequest(url) {
  return new Promise((resolve, reject) => {
    http.get(url, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        resolve(data);
      });
    }).on('error', (err) => {
      reject(err);
    });
  });
}

3. Write a Node.js function that accepts an array of numbers and returns the sum of all the numbers.

function calculateSum(numbers) {
  return numbers.reduce((sum, num) => sum + num, 0);
}

4. Write a Node.js function that accepts a string and checks if it is a palindrome (reads the same forwards and backwards).

function isPalindrome(str) {
  const reversed = str.split('').reverse().join('');
  return str === reversed;
}

5. Write a Node.js function that accepts an array of strings and sorts them in alphabetical order.

function sortStringsAlphabetically(strings) {
  return strings.sort();
}

6. Write a Node.js function that accepts a string and returns the count of occurrences of each character in the string as an object.

function countCharacterOccurrences(str) {
  const occurrences = {};
  
  for (const char of str) {
    occurrences[char] = occurrences[char] ? occurrences[char] + 1 : 1;
  }
  
  return occurrences;
}

7. Write a Node.js function that accepts a number and checks if it is a prime number.

function isPrimeNumber(num) {
  if (num <= 1) {
    return false;
  }
  
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) {
      return false;
    }
  }
  
  return true;
}

8. Write a Node.js function that accepts an array of objects and sorts them based on a specified property in ascending order.

function sortByProperty(objects, property) {
  return objects.sort((a, b) => a[property] - b[property]);
}

9. Write a Node.js function that accepts a string and capitalizes the first letter of each word.

function capitalizeFirstLetters(str) {
  return str.replace(/\b\w/g, (match) => match.toUpperCase());
}

10. Write a Node.js function to generate a random integer between a specified minimum and maximum value.

function generateRandomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.