Nodejs Practice Questions

Nodejs Practice Questions

1. What is Node.js?

Node.js is an open-source, cross-platform runtime environment that allows developers to execute JavaScript code outside of a web browser. Built on Chrome's V8 engine, it is designed for building scalable, high-performance network applications using a non-blocking, event-driven architecture.

2. What is the difference between Node.js and JavaScript in the browser?

3. What is the role of the package.json file in a Node.js project?

The package.json file is a manifest for a Node.js project. It includes metadata about the project, dependencies, scripts, and configuration. It is essential for managing packages and sharing the project.

4. What are some common Node.js modules and their uses?

5. What is the difference between synchronous and asynchronous programming in Node.js?

6. Explain the concept of an Event Loop in Node.js.

The Event Loop is a mechanism that handles asynchronous operations in Node.js. It processes callbacks from the event queue, ensuring non-blocking execution. It cycles through phases such as timers, I/O callbacks, idle preparation, poll, check, and close callbacks.

7. What is the purpose of the require function in Node.js?

The require function is used to import modules, libraries, or local files into a Node.js application. For example, const fs = require('fs');.

8. How do you export and import modules in Node.js?

// Export
module.exports = { greet: () => console.log("Hello!") };

// Import
const utils = require('./utils');
utils.greet();

9. What is npm, and how is it used in Node.js?

npm (Node Package Manager) is a tool to manage Node.js packages. It is used to install, update, and manage project dependencies.

10. What is the difference between npm install --save and npm install --save-dev?

11. What are callbacks in Node.js, and how are they used?

Callbacks are functions passed as arguments to other functions, executed after an asynchronous task completes.

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

12. What are Promises in Node.js, and how do they improve asynchronous code?

Promises represent the eventual completion or failure of an asynchronous operation, improving readability over callbacks by avoiding "callback hell."

fs.promises.readFile('file.txt')
  .then(data => console.log(data.toString()))
  .catch(err => console.error(err));

13. Explain the concept of async/await in Node.js.

async/await is a syntactic sugar over Promises, enabling asynchronous code to look synchronous for better readability.

async function readFile() {
  try {
    const data = await fs.promises.readFile('file.txt');
    console.log(data.toString());
  } catch (err) {
    console.error(err);
  }
}
readFile();

14. How does Node.js handle file system operations?

Node.js uses the fs module for file system operations:

15. What is middleware in the context of Node.js?

Middleware in Node.js is a function executed during the request-response cycle in a web application. It is commonly used in Express.js to handle requests, perform authentication, and process responses.

16. What is Express.js, and how is it related to Node.js?

Express.js is a web application framework for Node.js, simplifying the process of building robust APIs and web applications by providing utilities like routing, middleware, and HTTP request handling.

17. How can you handle errors in Node.js applications?

18. What is a RESTful API, and how can you create one with Node.js?

A RESTful API is an architecture for designing networked applications. Using Express.js, you can create RESTful endpoints:

const express = require('express');
const app = express();
app.get('/api/data', (req, res) => res.json({ key: 'value' }));
app.listen(3000);

19. How do you use environment variables in a Node.js application?

Environment variables store configuration values, accessed via process.env. Use libraries like dotenv to manage them.

require('dotenv').config();
console.log(process.env.MY_VARIABLE);

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

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

The buffer module in Node.js is used to handle binary data directly. It allows reading and writing binary data in streams or file operations without converting to strings.

const buffer = Buffer.from('Hello');
console.log(buffer.toString()); // Outputs 'Hello'

22. What is the difference between spawn, exec, and fork in Node.js?

23. What are streams in Node.js, and why are they useful?

Streams are objects for handling continuous data flows. They are efficient for I/O operations as they process data in chunks rather than loading the entire data into memory.

24. What are child processes in Node.js?

Child processes enable running multiple tasks concurrently by spawning separate processes. They can communicate using IPC (Inter-Process Communication).

const { spawn } = require('child_process');
const child = spawn('ls', ['-lh']);
child.stdout.on('data', data => console.log(data.toString()));

25. What is the difference between process.env and process.argv?

26. Explain clustering in Node.js.

Clustering allows you to utilize multi-core CPUs by spawning multiple worker processes running on the same port to share the load. The cluster module handles this functionality.

const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.fork(); // Create worker process
} else {
  console.log('Worker process running');
}

27. What are the differences between CommonJS and ES6 modules?

28. What is the use of the crypto module in Node.js?

The crypto module provides cryptographic functionality for securing data, such as hashing, encryption, and decryption.

const crypto = require('crypto');
const hash = crypto.createHash('sha256').update('password').digest('hex');
console.log(hash);

29. How does Node.js handle concurrency?

Node.js uses the event loop and libuv library to handle concurrency with a single-threaded non-blocking architecture. Long-running tasks, such as I/O, are offloaded to the thread pool or system kernel.

30. What is a namespace in Node.js?

Namespaces are used to organize and group related code to avoid global variable conflicts. For example, using modules effectively acts as a namespace.

31. How does the "path" module work in Node.js?

The path module provides utilities for working with file and directory paths.

const path = require('path');
const fullPath = path.join(__dirname, 'file.txt');
console.log(fullPath);

32. What are event emitters in Node.js?

Event emitters are part of the events module and are used to handle and trigger custom events in Node.js.

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', () => console.log('Hello!'));
emitter.emit('greet');

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

The util module provides utility functions like promisify for converting callback-based functions into Promises.

const util = require('util');
const readFile = util.promisify(fs.readFile);
readFile('file.txt').then(data => console.log(data.toString()));

34. How do you implement logging in Node.js?

Logging can be implemented using console, third-party libraries like winston, or writing logs to files with fs.

35. What is the difference between readFile and createReadStream?

36. What is a microservice, and how does Node.js support it?

A microservice is an independent service that performs specific tasks. Node.js supports microservices through lightweight frameworks like Express and its ability to handle multiple APIs efficiently.

37. What is a WebSocket in Node.js?

A WebSocket is a protocol for real-time, full-duplex communication. Node.js implements WebSockets using libraries like ws.

const WebSocket = require('ws');
const ws = new WebSocket.Server({ port: 8080 });
ws.on('connection', socket => socket.send('Hello!'));

38. How do you secure a Node.js application?

39. What is the purpose of the "worker_threads" module?

The worker_threads module enables running JavaScript code in parallel threads, useful for CPU-intensive tasks.

const { Worker } = require('worker_threads');
new Worker('./worker.js');

40. What is the difference between middleware and controllers in Node.js?

41. What is the difference between "streams" and "buffers" in Node.js?

Streams are more memory-efficient and are ideal for large-scale data handling, unlike buffers which load the entire data into memory.

42. What is the concept of backpressure in Node.js streams?

Backpressure occurs when the writable stream cannot process data as fast as it is received from the readable stream. It ensures the system doesn't overwhelm memory by pausing the data flow until the writable stream is ready.

const readable = fs.createReadStream('largeFile');
const writable = fs.createWriteStream('outputFile');
readable.pipe(writable); // Handles backpressure automatically

43. What are "ticks" and "microtasks" in Node.js?

"Ticks" refer to the tasks queued by process.nextTick(), executed before the next Event Loop phase. "Microtasks" include Promises and process.nextTick tasks, which are executed before other asynchronous operations.


process.nextTick(() => console.log('Tick'));
Promise.resolve().then(() => console.log('Microtask'));
setTimeout(() => console.log('Macro task'), 0);
// Output: Tick, Microtask, Macro task

44. What is the difference between "readable.pipe()" and "readable.on('data')"?

45. What is the difference between "cluster" and "worker_threads" modules in Node.js?

Clusters are for multi-process architectures, whereas worker threads are for multi-threaded operations.

46. Explain the term "head-of-line blocking" in the context of Node.js.

Head-of-line blocking occurs when one task in the queue blocks the execution of subsequent tasks. In Node.js, this can happen with synchronous operations or improper asynchronous handling, leading to delays in event loop processing.

47. What is the role of libuv in Node.js?

libuv is a library that provides the platform-agnostic, non-blocking I/O model in Node.js. It powers the Event Loop, thread pool, and handles low-level operations like file systems, network requests, and timers.

48. What are domain modules in Node.js?

The domain module provides a way to handle errors across different asynchronous operations. Although deprecated, it is still found in older applications for managing error-handling boundaries.

const domain = require('domain');
const d = domain.create();
d.on('error', err => console.error('Handled:', err));
d.run(() => { throw new Error('Something went wrong!'); });

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

The zlib module provides compression and decompression functionalities using algorithms like Gzip and Deflate. It is useful for reducing data transfer sizes.

const zlib = require('zlib');
const gzip = zlib.createGzip();
fs.createReadStream('file.txt').pipe(gzip).pipe(fs.createWriteStream('file.txt.gz'));

50. What are "sticky sessions," and how are they implemented in Node.js?

Sticky sessions ensure a user’s requests are routed to the same server instance in a load-balanced environment. This can be achieved using cookie-based session affinity or libraries like socket.io for stateful connections.

const session = require('express-session');
app.use(session({ secret: 'mySecret', resave: false, saveUninitialized: true }));