HTML & JS Topic

Node.js Interview Questions 

Core Node.js Concepts

1. What is Node.js and how does it work?

Answer: Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js operates on a single thread using event looping, allowing it to handle multiple concurrent connections efficiently.

2. Explain the event loop in Node.js

Answer: The event loop is what allows Node.js to perform non-blocking I/O operations. It's a single-threaded loop that listens for events (like I/O operations) and executes their callback functions when they're complete. The event loop has different phases: timers, pending callbacks, idle/prepare, poll, check, and close callbacks.

3. What is the difference between blocking and non-blocking code?

Answer: Blocking code executes synchronously, where each operation must complete before moving to the next. Non-blocking code executes asynchronously, allowing the program to continue executing other operations while waiting for I/O operations to complete.

4. What are streams in Node.js?

Answer: Streams are objects that let you read/write data continuously. Types include:

  • Readable (for reading)

  • Writable (for writing)

  • Duplex (both read/write)

  • Transform (modifies data while reading/writing)

javascript

const fs = require('fs');
const readableStream = fs.createReadStream('file.txt');

5. Explain the difference between require() and import

Answer: require() is CommonJS syntax (Node.js default), synchronous, and can be called anywhere. import is ES6 syntax, asynchronous, and must be at the top level of the file. Node.js supports ES6 modules with .mjs extension or "type": "module" in package.json.

6. What is the purpose of package.json?

Answer: package.json is a manifest file containing metadata about the project: dependencies, scripts, version, author, license, and configuration. It's essential for dependency management and project configuration.

7. Explain middleware in Express.js

Answer: Middleware are functions that have access to request, response, and the next middleware function. They can execute code, modify request/response, end the request-response cycle, or call the next middleware.

javascript

app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

8. What is REPL in Node.js?

Answer: REPL stands for Read-Eval-Print Loop. It's an interactive programming environment that takes single user inputs, executes them, and returns the result. Access it by typing node in the terminal.

9. How does error handling work in Node.js?

Answer: Errors can be handled using:

  • Try-catch blocks (for synchronous code)

  • Error-first callbacks

  • Promises with .catch()

  • Async/await with try-catch

  • Event emitters with error event listeners

10. What is clustering in Node.js?

Answer: Clustering allows you to create multiple instances of your application (workers) to utilize multi-core systems. The master process distributes incoming connections among workers.

javascript

const cluster = require('cluster');
const os = require('os');

if (cluster.isMaster) {
  for (let i = 0; i < os.cpus().length; i++) {
    cluster.fork();
  }
} else {
  // Worker process
}

Asynchronous Programming

11. What are callbacks?

Answer: Callbacks are functions passed as arguments to other functions, to be executed later when an asynchronous operation completes. Node.js uses error-first callbacks where the first parameter is reserved for an error object.

12. Explain promises in Node.js

Answer: Promises represent the eventual completion (or failure) of an asynchronous operation. They have three states: pending, fulfilled, or rejected.

javascript

const promise = new Promise((resolve, reject) => {
  // async operation
  if (success) resolve(value);
  else reject(error);
});

13. What is async/await?

Answer: Async/await is syntactic sugar over promises that makes asynchronous code look synchronous. async functions return a promise, and await pauses execution until the promise resolves.

javascript

async function fetchData() {
  try {
    const data = await someAsyncOperation();
    return data;
  } catch (error) {
    console.error(error);
  }
}

14. What is the difference between process.nextTick() and setImmediate()?

Answer: process.nextTick() executes in the current event loop iteration, immediately after the current operation. setImmediate() executes in the next iteration of the event loop. nextTick() has higher priority.

15. Explain Promise.all() and Promise.race()

Answer: Promise.all() waits for all promises to resolve or any to reject. Promise.race() waits for the first promise to settle (resolve or reject).

File System & Buffers

16. How do you read a file in Node.js?

Answer: Using the fs module:

javascript

const fs = require('fs');

// Synchronous
const data = fs.readFileSync('file.txt', 'utf8');

// Asynchronous
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// With promises
fs.promises.readFile('file.txt', 'utf8').then(data => console.log(data));

17. What are buffers in Node.js?

Answer: Buffers are temporary storage for binary data when dealing with TCP streams, file system operations, etc. They represent fixed-size chunks of memory allocated outside the V8 heap.

javascript

const buf = Buffer.from('Hello', 'utf8');

18. Explain the difference between fs.readFile() and fs.createReadStream()

Answer: fs.readFile() reads the entire file into memory, which is inefficient for large files. fs.createReadStream() reads files in chunks using streams, making it memory-efficient for large files.

Modules

19. What is the difference between module.exports and exports?

Answer: module.exports is the actual object that gets exported. exports is a reference to module.exports. Assigning to exports breaks the reference, so always use module.exports for assignment.

20. How does module caching work in Node.js?

Answer: Node.js caches modules after the first require(). Subsequent require() calls return the cached version. The cache can be inspected via require.cache.

21. What are core modules in Node.js?

Answer: Core modules are built-in modules that come with Node.js installation, like fs, http, path, os, events, etc. They don't need to be installed separately.

22. Explain the __dirname and __filename variables

Answer: __dirname contains the directory name of the current module. __filename contains the file name of the current module. They're useful for creating paths relative to the current file.

Event Emitters

23. What are Event Emitters in Node.js?

Answer: Event Emitters are objects that can emit named events and register listener functions. Many Node.js core modules inherit from EventEmitter.

javascript

const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => console.log('Event fired!'));
myEmitter.emit('event');

24. Difference between on() and once() methods

Answer: on() registers a listener that will be called every time the event is emitted. once() registers a listener that will be called only the first time the event is emitted.

HTTP & Networking

25. How to create an HTTP server in Node.js?

Answer: Using the http module:

javascript

const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World');
});
server.listen(3000);

26. What is the difference between req.url and req.path in Express?

Answer: req.url contains the entire URL string including query parameters. req.path contains only the path portion (Express only).

27. How to handle query parameters in Express?

Answer: Using req.query object:

javascript

// URL: /users?name=John&age=30
app.get('/users', (req, res) => {
  const name = req.query.name;
  const age = req.query.age;
});

28. What are route parameters in Express?

Answer: Route parameters are named URL segments used to capture values at specific positions:

javascript

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
});

Database & ORM

29. How to connect to MongoDB in Node.js?

Answer: Using Mongoose (ODM):

javascript

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

30. What is an ORM/ODM?

Answer: ORM (Object-Relational Mapping) and ODM (Object-Document Mapping) are techniques to convert data between incompatible type systems. Examples: Sequelize (SQL), Mongoose (MongoDB).

31. Explain connection pooling in databases

Answer: Connection pooling maintains a cache of database connections that can be reused, reducing the overhead of establishing new connections for each request.

Authentication & Security

32. What is JWT (JSON Web Token)?

Answer: JWT is a compact, URL-safe means of representing claims to be transferred between two parties. It consists of three parts: header, payload, and signature, separated by dots.

33. How to implement authentication in Node.js?

Answer: Using packages like Passport.js, bcrypt for password hashing, and JWT for token-based authentication.

34. What is CORS and how to enable it in Express?

Answer: CORS (Cross-Origin Resource Sharing) is a mechanism that allows restricted resources to be requested from another domain. Enable with:

javascript

const cors = require('cors');
app.use(cors());

Testing & Debugging

35. What testing frameworks are used in Node.js?

Answer: Popular frameworks include Jest, Mocha, Jasmine, and Chai for assertions. SuperTest for HTTP testing.

36. How to debug Node.js applications?

Answer: Using:

  • console.log()

  • Node.js built-in debugger (node inspect)

  • Chrome DevTools (node --inspect)

  • VS Code debugger

  • Third-party tools like ndb

37. What is unit testing vs integration testing?

Answer: Unit testing tests individual components in isolation. Integration testing tests how components work together.

Performance & Optimization

38. How to handle memory leaks in Node.js?

Answer:

  • Use tools like Chrome DevTools Memory Profiler

  • Avoid global variables

  • Clear intervals and timeouts

  • Remove event listeners

  • Use streams for large data

39. What is the node --max-old-space-size flag?

Answer: It sets the maximum size of the old memory section in megabytes. Useful for increasing memory limits: node --max-old-space-size=4096 app.js

40. Explain the Node.js garbage collection

Answer: Node.js uses V8's garbage collector with two main types: Scavenge (fast, collects new space) and Mark-Sweep/Compact (slow, collects old space).

Process & OS

41. What is the process object?

Answer: process is a global object providing information about the current Node.js process. It includes methods like process.exit(), process.cwd(), and properties like process.env, process.argv.

42. How to access environment variables in Node.js?

Answer: Using process.env object:

javascript

const port = process.env.PORT || 3000;
const apiKey = process.env.API_KEY;

43. What is process.nextTick() used for?

Answer: It allows you to schedule a callback to be invoked in the next iteration of the event loop, before any I/O operations or timers.

Error Handling

44. What is the error-first callback pattern?

Answer: A convention where the first parameter of a callback function is reserved for an error object. If no error, it's null or undefined.

javascript

function callback(err, data) {
  if (err) {
    // handle error
  }
  // process data
}

45. How to handle uncaught exceptions in Node.js?

Answer: Using process.on('uncaughtException') and process.on('unhandledRejection'):

javascript

process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
  process.exit(1);
});

Tools & Best Practices

46. What is NPM and what does it do?

Answer: NPM (Node Package Manager) is the default package manager for Node.js. It manages project dependencies, scripts, and package distribution.

47. What is the difference between dependencies and devDependencies?

Answer: dependencies are packages required for production. devDependencies are packages required only for development and testing.

48. What is the purpose of package-lock.json?

Answer: It locks the exact version of each installed package and its dependencies, ensuring consistent installs across different environments.

49. What are some best practices for Node.js development?

Answer:

  • Use async/await or promises instead of callbacks

  • Handle errors properly

  • Use environment variables for configuration

  • Implement logging

  • Use process managers (PM2)

  • Follow the 12-factor app methodology

  • Implement proper security measures

50. What is the difference between npm and npx?

Answer: npm is a package manager for installing packages. npx is a tool for executing packages without installing them globally. It downloads, executes, and then removes the package.

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?