Introduction:
Node.js has become a cornerstone in modern web development, powering numerous applications with its asynchronous, event-driven architecture. If you’re gearing up for a Node.js interview, this guide is your go-to resource. We’ve compiled an extensive list of over 100 interview questions, each accompanied by detailed answers and practical examples to help you deepen your understanding and prepare effectively.
Node.js Basics:
- What is Node.js?
- Node.js is an open-source, server-side JavaScript runtime environment built on the V8 JavaScript engine.
- Explain the event-driven architecture of Node.js.
- Node.js utilizes an event-driven, non-blocking I/O model. Events are emitted, and callbacks handle them asynchronously.
Practical Example:
const fs = require('fs'); fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
- How does Node.js differ from traditional server-side technologies?
- Unlike traditional server-side technologies, Node.js is non-blocking, allowing concurrent connections and optimal resource utilization.
- Explain the role of the V8 JavaScript engine in Node.js.
- V8 is Google’s open-source JavaScript engine that powers Node.js. It compiles JavaScript to machine code for faster execution.
Practical Example:
console.log(v8.getHeapStatistics());
- What is npm?
- npm (Node Package Manager) is the default package manager for Node.js. It facilitates package installation, version management, and dependency resolution.
- How does the ‘require’ function work in Node.js?
- The ‘require’ function is used to include external modules. Node.js searches for modules in its ‘node_modules’ directory.
Practical Example:
const http = require('http');
- What is the purpose of the ‘global’ object in Node.js?
- The ‘global’ object represents the global scope and contains global variables. However, it is recommended to avoid using it excessively.
Practical Example:
global.appName = 'MyNodeApp';
- How can you handle errors in Node.js?
- Errors can be handled using try-catch blocks or by passing an error parameter to callback functions.
Practical Example:
try { // Code that might throw an error } catch (error) { console.error(error); }
- What is the ‘process’ object in Node.js?
- The ‘process’ object provides information about the Node.js process. It can be used to access command-line arguments, environment variables, and more.
Practical Example:
console.log(process.env.NODE_ENV);
- Explain the concept of ‘Streams’ in Node.js.
- Streams provide an efficient way to read or write large amounts of data. They can be readable, writable, or duplex.
Practical Example:
const fs = require('fs');
const readStream = fs.createReadStream('largefile.txt');
Modules and Dependency Management:
- What are the core modules in Node.js?
- Core modules are built-in modules provided by Node.js, such as ‘fs’, ‘http’, and ‘util’.
Practical Example:
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => { /* ... */ });
- Explain the difference between ‘exports’ and ‘module.exports’.
- ‘exports’ is a shorthand for ‘module.exports’, but if ‘exports’ is reassigned, it loses its connection to ‘module.exports’.
Practical Example:
// In a module
exports.sayHello = () => console.log('Hello');
// or
module.exports = { sayHello: () => console.log('Hello') };
- How does npm shrinkwrap work?
- ‘npm shrinkwrap’ creates a ‘npm-shrinkwrap.json’ file, fixing the versions of all dependencies, ensuring consistent installations across different environments.
Practical Example:
npm shrinkwrap
- What is the purpose of the ‘package.json’ file?
- ‘package.json’ contains metadata about the project and its dependencies. It is used by npm to manage project settings and dependencies.
Practical Example:
{
"name": "my-node-app",
"version": "1.0.0",
"dependencies": {
"express": "^4.17.1"
}
}
- How can you prevent ‘Callback Hell’ in Node.js?
- Use techniques like modularization, named functions, and Promises to avoid nesting callbacks.
Practical Example:
readFile('file1.txt', (data1) => {
readFile('file2.txt', (data2) => {
// ...
});
});
Asynchronous Programming:
- Explain the concept of the ‘Event Loop’ in Node.js.
- The event loop manages asynchronous operations, constantly checking the message queue for events to execute.
Practical Example:
setInterval(() => console.log('Event Loop'), 1000);
- What are Promises in Node.js?
- Promises represent the eventual completion or failure of an asynchronous operation, providing a cleaner alternative to callbacks.
Practical Example:
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data fetched'), 2000);
});
};
- How does ‘async/await’ simplify asynchronous code in Node.js?
- ‘async/await’ is a syntax sugar for handling Promises, making asynchronous code more readable and easier to write.
Practical Example:
const fetchData = async () => {
const data = await fetchData();
console.log(data);
};
- What is the purpose of the ‘Callback’ function in Node.js?
- Callback functions are used to handle asynchronous operations, ensuring that a function is executed after the completion of an operation.
Practical Example:
const fetchData = (callback) => {
setTimeout(() => callback('Data fetched'), 2000);
};
- How does the ‘util.promisify’ function work in Node.js?
- ‘util.promisify’ converts callback-based functions into Promise-based functions, simplifying asynchronous code.
Practical Example:
const util = require('util');
const fs = require('fs
');
const readFileAsync = util.promisify(fs.readFile);
Express.js Framework:
- What is Express.js, and why is it popular?
- Express.js is a minimal and flexible Node.js web application framework, simplifying the process of building robust web applications.
Practical Example:
const express = require('express');
const app = express();
- Explain middleware in Express.js.
- Middleware functions are functions that have access to the request, response, and the next middleware function. They can modify the request or response, terminate the request-response cycle, or call the next middleware in the stack.
Practical Example:
const logMiddleware = (req, res, next) => {
console.log('Request received at:', new Date());
next();
};
app.use(logMiddleware);
- How to handle routing in Express.js?
- Express.js uses the ‘app.get’, ‘app.post’, ‘app.put’, and ‘app.delete’ methods to define routes for different HTTP methods.
Practical Example:
app.get('/api/users', (req, res) => {
// Handle GET request for users
});
- What is the role of ‘app.use’ in Express.js?
- ‘app.use’ is used to mount middleware functions. It is executed every time a request is made, regardless of the HTTP method.
Practical Example:
app.use(express.json());
- How to serve static files in Express.js?
- ‘express.static’ is used to serve static files. It takes the root directory as an argument and serves files from there.
Practical Example:
app.use(express.static('public'));
- Explain the concept of ‘Express.js Router’.
- Express Router is a middleware that allows defining route handlers in separate files and then combining them into the main application.
Practical Example:
// routes/users.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
// Handle GET request for users
});
module.exports = router;
- What is the purpose of ‘body-parser’ middleware in Express.js?
- ‘body-parser’ parses incoming request bodies and makes the parsed data available under ‘req.body’.
Practical Example:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
- How to implement error handling in Express.js?
- Error handling middleware can be implemented by defining a middleware function with four parameters (err, req, res, next).
Practical Example:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
- What is the purpose of the ‘express-session’ middleware?
- ‘express-session’ is used to manage user sessions in Express.js applications.
Practical Example:
const session = require('express-session');
app.use(session({ secret: 'mySecret', resave: false, saveUninitialized: true }));
- How to implement route parameters in Express.js?
- Route parameters are defined by placing a colon before the parameter name in the route URL.
Practical Example:
app.get('/api/users/:id', (req, res) => {
const userId = req.params.id;
// Handle request for user with specified ID
});
RESTful APIs with Node.js:
- What is RESTful architecture?
- REST (Representational State Transfer) is an architectural style that uses standard HTTP methods for CRUD operations.
- How to create a RESTful API using Node.js and Express?
- Express.js provides a convenient way to define routes and handle HTTP methods for creating a RESTful API.
Practical Example:
// routes/books.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
// Get all books
});
router.post('/', (req, res) => {
// Create a new book
});
router.put('/:id', (req, res) => {
// Update a book
});
router.delete('/:id', (req, res) => {
// Delete a book
});
module.exports = router;
- Explain the concept of ‘CORS’ and how to handle it in Express.js.
- Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers. It can be handled in Express.js using the ‘cors’ middleware.
Practical Example:
const cors = require('cors');
app.use(cors());
- How to handle file uploads in a Node.js/Express application?
- File uploads can be handled using the ‘multer’ middleware, which facilitates the handling of ‘multipart/form-data’.
Practical Example:
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
// Handle uploaded file
});
- What is the purpose of the ‘body-parser’ middleware in Express.js when working with APIs?
- ‘body-parser’ is used to parse the request body, making the data available under ‘req.body’ for handling POST and PUT requests.
Practical Example:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
- How to implement pagination in a Node.js/Express API?
- Pagination can be implemented by using query parameters like ‘page’ and ‘limit’ to control the number of items per page and the current page.
Practical Example:
app.get('/api/users', (req, res) => {
const page = req.query.page || 1;
const limit = req.query.limit || 10;
// Retrieve users with pagination
});
- What is JWT (JSON Web Token) and how is it used in Node.js/Express?
- JWT is a compact, URL-safe means of representing claims between two parties. It is commonly used for authentication in web applications.
Practical Example:
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 1 }, 'secretKey', { expiresIn: '1h' });
- How to implement authentication in a Node.js/Express API?
- Authentication can be implemented using middleware functions to verify JWT tokens or using passport.js for more advanced authentication strategies.
Practical Example:
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
- Explain the concept of ‘Swagger’ and how it can be used with Express.js for API documentation.
- Swagger is a tool for documenting APIs. In Express.js, the ‘swagger-jsdoc’ and ‘swagger-ui-express’ packages can be used to generate and display Swagger documentation.
Practical Example:
const swaggerJSDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const specs = swaggerJSDoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
- How to handle authentication and authorization in a Node.js/Express API?
- Authentication can be handled using middleware functions to check user credentials. Authorization can be managed by verifying user roles or permissions.
Practical Example:
const authenticate = (req, res, next) => {
// Check user credentials and attach user object to req
// ...
next();
};
app.get('/api/secure', authenticate, (req, res) => {
// Handle secure API endpoint
});
Security in Node.js:
- What are the common security best practices in Node.js?
- Security best practices include input validation, parameterized queries to prevent SQL injection, secure password storage, and regular security audits.
Practical Example:
const sql = 'SELECT * FROM users WHERE username = ? AND password = ?';
connection.query(sql, [username, password], (err, results) => {
// Handle results
});
- How to prevent SQL injection in a Node.js application?
- SQL injection can be prevented by using parameterized queries or prepared statements.
Practical Example:
const sql = 'SELECT * FROM users WHERE username = ? AND password = ?';
connection.query(sql, [username, password], (err, results) => {
// Handle results
});
- Explain Cross-Site Scripting (XSS) and how to prevent it in Node.js applications.
- XSS is a security vulnerability where attackers inject malicious scripts into web pages. It can be prevented by validating and sanitizing user input.
Practical Example:
const sanitizeHtml = require('sanitize-html');
const sanitizedInput = sanitizeHtml(userInput, { allowedTags: [], allowedAttributes: {} });
- What is CSRF (Cross-Site Request Forgery) and how to prevent it in Node.js applications?
- CSRF is an attack where a malicious website sends a request on behalf of a user who is authenticated on another website. It can be prevented using anti-CSRF tokens.
Practical Example:
const csrf = require('csurf');
app.use(csrf());
- How to secure password storage in a Node.js application?
- Passwords should be hashed using strong cryptographic algorithms, and a unique salt should be used for each user to prevent rainbow table attacks.
Practical Example:
const bcrypt = require('bcrypt');
const saltRounds = 10;
bcrypt.hash('userPassword', saltRounds, (err, hash) => {
// Store hash in the database
});
- What is HTTPS and why is it important for security in Node.js applications?
- HTTPS (Hypertext Transfer Protocol Secure) encrypts data exchanged between the client and server, ensuring the confidentiality and integrity of the communication.
Practical Example:
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('path/to/private-key.pem'),
cert: fs.readFileSync('path/to/certificate.pem'),
};
const server = https.createServer(options, (req, res) => { /* ... */ });
- How to implement rate limiting in a Node.js application to prevent abuse?
- Rate limiting can be implemented using middleware or external services to restrict the number of requests a client can make within a specified time frame.
Practical Example:
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
app.use(limiter);
- Explain the importance of secure session management in Node.js applications.
- Secure session management involves using secure, randomly generated session identifiers, setting secure cookies, and enforcing session timeouts to enhance application security.
Practical Example:
const session = require('express-session');
app.use(session({
secret: 'mySecret',
resave: false,
saveUninitialized: true,
cookie: { secure: true },
}));
- How to protect against NoSQL injection in a Node.js application using MongoDB?
- NoSQL injection can be prevented by validating and sanitizing user input and using parameterized queries or ORM libraries that automatically escape user input.
Practical Example:
const userQuery = { username: userInput };
User.findOne(userQuery, (err, user) => { /* ... */ });
- What is ‘Helmet’ and how does it enhance security in Express.js applications?
- ‘Helmet’ is a middleware for Express.js that helps secure web applications by setting various HTTP headers to prevent common vulnerabilities.
Practical Example:
const helmet = require('helmet');
app.use(helmet());
Testing in Node.js:
- Explain the importance of testing in Node.js.
- Testing is crucial to ensure the reliability and stability of Node.js applications, catching bugs and regressions early in the development process.
- How to perform unit testing in Node.js using Mocha and Chai?
- Mocha is a test framework, and Chai is an assertion library. They are often used together for unit testing.
Practical Example:
const assert = require('chai').assert;
describe('Math operations', () => {
it('should add two numbers correctly', () => {
assert.equal(2 + 3, 5);
});
});
- What is ‘Supertest’ and how can it be used for API testing in Node.js?
- ‘Supertest’ is a testing library that simplifies the testing of HTTP requests in Node.js applications.
Practical Example:
const request = require('supertest');
const app = require('../app');
describe('GET /api/users', () => {
it('responds with JSON', (done) => {
request(app)
.get('/api/users')
.set('Accept', '
application/json')
.expect('Content-Type', /json/)
.expect(200, done);
});
});
- How to mock dependencies for unit testing in Node.js?
- Dependencies can be mocked using libraries like ‘sinon’ or by creating manual mocks.
Practical Example:
const sinon = require('sinon');
const userService = require('../services/userService');
describe('User Service', () => {
it('should get user by ID', () => {
const mock = sinon.mock(userService);
mock.expects('getUserById').once().withArgs(1).returns({ id: 1, name: 'John' });
const user = userService.getUserById(1);
mock.verify();
assert.deepEqual(user, { id: 1, name: 'John' });
});
});
- How to automate and perform end-to-end testing in a Node.js application?
- End-to-end testing can be automated using tools like ‘Puppeteer’ or ‘Cypress’ to simulate user interactions and validate the behavior of the entire application.
Practical Example:
const puppeteer = require('puppeteer');
describe('End-to-end Test', () => {
it('should navigate to the home page', async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://localhost:3000/');
const title = await page.title();
assert.equal(title, 'My Node App');
await browser.close();
});
});
- How to use ‘Jest’ for testing in a Node.js application?
- ‘Jest’ is a popular JavaScript testing framework that can be used for unit testing, mocking, and snapshot testing.
Practical Example:
const math = require('../math');
describe('Math operations', () => {
it('should add two numbers correctly', () => {
expect(math.add(2, 3)).toBe(5);
});
});
- What is code coverage, and how can it be measured in a Node.js application?
- Code coverage measures the percentage of code that has been executed during testing. Tools like ‘Istanbul’ can be used to generate code coverage reports.
Practical Example:
npx istanbul cover ./node_modules/mocha/bin/_mocha -- test/**/*.js
- How to perform load testing on a Node.js application?
- Load testing can be done using tools like ‘Artillery’ or ‘Apache JMeter’ to simulate multiple users and analyze the performance of the application under load.
Practical Example:
config:
target: 'http://localhost:3000'
phases:
- duration: 60
arrivalRate: 5
scenarios:
- flow:
- get:
url: '/'
- What is snapshot testing, and how can it be used in a Node.js application?
- Snapshot testing captures the output of a component and saves it as a reference for future comparisons, detecting unexpected changes.
Practical Example:
test('renders correctly', () => {
const tree = renderer.create(<MyComponent />).toJSON();
expect(tree).toMatchSnapshot();
});
- How to use continuous integration (CI) tools like Jenkins or Travis CI with a Node.js application?
- CI tools can be configured to automatically build, test, and deploy Node.js applications when changes are pushed to version control repositories.
Practical Example:
language: node_js
node_js:
- 14
script:
- npm install
- npm test
Scaling and Performance Optimization:
- How can you scale a Node.js application?
- Scaling can be achieved through horizontal scaling by deploying multiple instances of the application and using load balancers to distribute incoming traffic.
- Explain the concept of clustering in Node.js for better performance.
- Clustering involves creating multiple instances (workers) of a Node.js process to take advantage of multi-core systems and improve application performance.
Practical Example:
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
for (let i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
} else {
// Worker code
// ...
}
- How to optimize memory usage in a Node.js application?
- Memory optimization can be achieved by monitoring and identifying memory leaks, using efficient data structures, and implementing garbage collection strategies.
Practical Example:
const memwatch = require('memwatch-next');
memwatch.on('leak', (info) => {
console.error('Memory leak detected:', info);
});
- Explain the role of a reverse proxy in Node.js deployment.
- A reverse proxy acts as an intermediary between client requests and the Node.js server, handling tasks such as load balancing, SSL termination, and serving static files.
Practical Example:
const express = require('express');
const app = express();
app.set('trust proxy', 1);
- How to implement caching to improve performance in a Node.js application?
- Caching can be implemented using in-memory caching, Redis, or other caching mechanisms to store frequently accessed data and reduce database or API calls.
Practical Example:
const cache = {};
const fetchData = async (key) => {
if (cache[key]) {
return cache[key];
}
const data = await fetchFromDatabaseOrAPI();
cache[key] = data;
return data;
};
- How to optimize the performance of database queries in a Node.js application?
- Database query optimization can be achieved by creating indexes, using appropriate data types, and optimizing complex queries.
Practical Example:
// Creating an index in MongoDB
db.users.createIndex({ username: 1 });
- What is connection pooling, and how can it be used in Node.js to improve database performance?
- Connection pooling involves reusing existing database connections instead of creating a new connection for each request, improving performance by reducing connection overhead.
Practical Example:
const { Pool } = require('pg');
const pool = new Pool({
user: 'user',
host: 'localhost',
database: 'mydatabase',
password: 'password',
port: 5432,
});
- How to optimize the serving of static files in a Node.js application?
- Optimizing static file serving can be done by using a reverse proxy, implementing caching headers, and serving static files from a CDN.
Practical Example:
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static(path.join(__dirname, 'public')));
- Explain the concept of microservices, and how can they be implemented in a Node.js application?
- Microservices involve breaking down a monolithic application into small, independent services that communicate through APIs. Each microservice focuses on a specific business capability.
Practical Example:
// User microservice
const express = require('express');
const app = express();
app.get('/api/users', (req, res) => {
// Get users
});
app.post('/api/users', (req, res) => {
// Create a new user
});
app.listen(3001);
- How to implement serverless architecture using Node.js?
- Serverless architecture involves using cloud providers like AWS Lambda to execute functions without managing server infrastructure.
Practical Example:
// AWS Lambda function
exports.handler = async (event, context) => {
// Function logic
};
Advanced Topics:
- What is WebSocket, and how can it be implemented in a Node.js application?
- WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It can be implemented in Node.js using libraries like ‘socket.io’.
Practical Example:
const socketIo = require('socket.io');
const io = socketIo(server);
io.on('connection', (socket) => {
console.log('A user connected');
});
- How to implement GraphQL in a Node.js application?
- GraphQL is a query language for APIs that allows clients to request only the data they need. It can be implemented in Node.js using libraries like ‘express-graphql’.
Practical Example:
const express = require('express');
const expressGraphQL = require('express-graphql');
const schema = require('./schema');
const app = express();
app.use('/graphql', expressGraphQL({ schema, graphiql: true }));
- Explain the concept of WebSockets and how they differ from HTTP.
- WebSockets provide full-duplex communication channels over a single TCP connection, allowing bidirectional communication between clients and servers. Unlike HTTP, WebSockets enable real-time communication.
- What is the role of ‘pm2’ in Node.js deployment, and how can it be used?
- ‘pm2’ is a process manager for Node.js applications that simplifies deployment by managing processes, enabling features like automatic restarts, scaling, and monitoring.
Practical Example:
pm2 start app.js
- How to handle environment variables securely in a Node.js application?
- Environment variables can be managed securely by using a package like ‘dotenv’ to load them from a ‘.env’ file and ensuring that sensitive information is not exposed.
Practical Example:
require('dotenv').config();
const apiKey = process.env.API_KEY;
- What is the ‘EventEmitter’ module in Node.js, and how can it be used?
- ‘EventEmitter’ is a core module in Node.js that facilitates the implementation of the observer pattern. It can be used to emit and handle custom events.
Practical Example:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('Event emitted');
});
myEmitter.emit('event');
- How to handle file uploads in a Node.js application using ‘multer’?
- ‘Multer’ is a middleware for handling ‘multipart/form-data’, commonly used for handling file uploads in Node.js applications.
Practical Example:
const express = require('express');
const multer = require('multer');
const app = express();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now());
},
});
const upload = multer({ storage: storage });
app.post('/upload', upload.single('file'), (req, res) => {
// Handle uploaded file
});
- What is ‘Passport.js,’ and how can it be used for authentication in a Node.js application?
- ‘Passport.js’ is a middleware for authentication in Node.js applications, supporting various authentication strategies, including local, OAuth, and OpenID.
Practical Example:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
(username, password, done) => {
// Validate user credentials
// ...
}
));
- How to handle sessions in a Node.js application?
- Sessions can be managed using the ‘express-session’ middleware, which stores session data on the server and assigns a session ID to the client.
Practical Example:
const session = require('express-session');
const app = express();
app.use(session({ secret: 'mySecret', resave: false, saveUninitialized: true }));
- What is ‘async_hooks’ in Node.js, and how can it be used for debugging?
- ‘async_hooks’ is a module in Node.js that provides an API for tracking the lifetime of asynchronous resources. It can be used for debugging and profiling asynchronous code.
Practical Example:
const async_hooks = require('async_hooks');
const asyncHook = async_hooks.createHook({
init: (asyncId, type, triggerAsyncId, resource) => {
console.log(`Init ${type} with ID ${asyncId}`);
},
destroy: (asyncId) => {
console.log(`Destroy with ID ${asyncId}`);
},
});
asyncHook.enable();
- Explain the concept of ‘child_process’ in Node.js and how it can be used.
- ‘child_process’ is a core module in Node.js that allows the execution of external processes. It can be used for tasks like running shell commands or spawning child processes.
Practical Example:
const { exec } = require('child_process');
exec('ls -l', (error, stdout, stderr) => {
console.log('Result:', stdout);
});
- What is ‘Worker Threads’ in Node.js, and how can they be used for parallelism?
- ‘Worker Threads’ is a module in Node.js that enables the creation of separate threads to perform parallel computations. It is useful for CPU-bound tasks.
Practical Example:
const { Worker } = require('worker_threads');
const worker = new Worker('worker.js');
worker.on('message', (message) => {
console.log('Received:', message);
});
worker.postMessage('Hello from main thread!');
- How to handle errors in asynchronous code in Node.js?
- Errors in asynchronous code can be handled using try-catch blocks, Promises with ‘.catch()’, or the ‘error’ event for event emitters.
Practical Example:
try {
const result = await asyncFunction();
console.log(result);
} catch (error) {
console.error('Error:', error);
}
- Explain the concept of ‘Promises’ in Node.js and how they differ from callbacks.
- ‘Promises’ are a pattern for handling asynchronous operations in a more readable and maintainable way compared to callbacks. They represent a value that may be available now, in the future, or never.
Practical Example:
const fetchData = () => new Promise((resolve, reject) => {
// Asynchronous operation
if (success) {
resolve(data);
} else {
reject(error);
}
});
fetchData()
.then((result) => console.log(result))
.catch((error) => console.error(error));
- What is the purpose of ‘npm’ in Node.js, and how can it be used for package management?
- ‘npm’ (Node Package Manager) is the default package manager for Node.js. It is used for installing, managing, and sharing JavaScript packages.
Practical Example:
npm install packageName
- How to debug Node.js applications using ‘debug’ module or built-in debugging tools?
- Node.js applications can be debugged using the ‘debug’ module for logging or by utilizing built-in debugging tools like ‘inspect’ and ‘inspect-brk’.
Practical Example:
// Using 'debug' module
const debug = require('debug')('myApp:server');
debug('This is a debug message');
- How to create custom middleware in Express.js?
- Custom middleware functions in Express.js can be created by defining functions with the parameters (req, res, next) and using them with ‘app.use()’.
Practical Example:
const customMiddleware = (req, res, next) => {
// Middleware logic
next();
};
app.use(customMiddleware);
- What is the purpose of the ‘url’ module in Node.js, and how can it be used?
- The ‘url’ module in Node.js provides utilities for URL resolution and parsing. It can be used to manipulate and parse URLs.
Practical Example:
const url = require('url');
const parsedUrl = url.parse('https://example.com/path?query=value', true);
console.log(parsedUrl.pathname); // Output: /path
- Explain the concept of middleware chaining in Express.js.
- Middleware chaining in Express.js involves using multiple middleware functions sequentially by passing them as arguments to ‘app.use()’ or specific routes.
Practical Example:
const middleware1 = (req, res, next) => {
console.log('Middleware 1');
next();
};
const middleware2 = (req, res, next) => {
console.log('Middleware 2');
next();
};
app.use(middleware1, middleware2);
- How to use ‘dotenv’ for managing environment variables in a Node.js application?
- ‘dotenv’ is a package that loads environment variables from a ‘.env’ file into ‘process.env’, making it easy to manage configuration settings.
Practical Example:
require('dotenv').config();
const apiKey = process.env.API_KEY;
- What is the purpose of the ‘crypto’ module in Node.js, and how can it be used for cryptographic operations?
- The ‘crypto’ module in Node.js provides cryptographic functionality. It can be used for hashing, HMAC, encryption, and decryption.
Practical Example:
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('Hello, world!');
const hashedValue = hash.digest('hex');
- How to deploy a Node.js application to a cloud platform like AWS, Heroku, or Azure?
- Node.js applications can be deployed to cloud platforms by creating a deployment package, configuring the platform-specific settings, and using deployment commands.
Practical Example:
# Deploying to Heroku
git push heroku main
- Explain the concept of ‘Middleware’ in Express.js and how it works.
- Middleware in Express.js are functions that have access to the request, response, and the next middleware function in the application’s request-response cycle. They can modify the request or response, terminate the cycle, or call the next middleware.
Practical Example:
const logMiddleware = (req, res, next) => {
console.log('Request received at:', new Date());
next();
};
app.use(logMiddleware);
- How to handle cross-origin requests in an Express.js application?
- Cross-Origin Resource Sharing (CORS) can be handled in an Express.js application using the ‘cors’ middleware, which adds the necessary headers to allow or restrict cross-origin requests.
Practical Example:
const cors = require('cors');
app.use(cors());
- Explain the concept of ‘cookie-parser’ middleware in Express.js.
- ‘cookie-parser’ is a middleware in Express.js used for parsing and setting cookies in the request and response objects. It simplifies the handling of cookies.
Practical Example:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
- How to implement WebSocket communication in an Express.js application using ‘socket.io’?
- WebSocket communication in Express.js can be implemented using the ‘socket.io’ library, which provides a simple API for real-time bidirectional communication between clients and the server.
Practical Example:
const http = require('http');
const express = require('express');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
io.on('connection', (socket) => {
console.log('A user connected');
});
server.listen(3000);
- How to implement a custom 404 page in an Express.js application?
- A custom 404 page in an Express.js application can be implemented by defining a middleware function that handles unknown routes and sets the appropriate status
code.
Practical Example:
const custom404 = (req, res) => {
res.status(404).send('Custom 404: Page Not Found');
};
app.use(custom404);
- Explain the concept of ‘Body Parser’ middleware in Express.js.
- ‘body-parser’ is a middleware in Express.js used for parsing the request body. It can parse JSON, URL-encoded, and raw request bodies.
Practical Example:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
- How to implement pagination in a Node.js/Express API?
- Pagination in a Node.js/Express API can be implemented by using query parameters like ‘page’ and ‘limit’ to control the number of items returned in each response.
Practical Example:
app.get('/api/users', (req, res) => {
const page = req.query.page || 1;
const limit = req.query.limit || 10;
const users = getUsers(page, limit);
res.json(users);
});
- What are serverless functions, and how can they be implemented in a Node.js application using platforms like AWS Lambda or Netlify Functions?
- Serverless functions are event-driven, ephemeral, and stateless compute units that are managed by a cloud provider. In a Node.js application, serverless functions can be implemented using platforms like AWS Lambda or Netlify Functions.
Practical Example:
// AWS Lambda function
exports.handler = async (event, context) => {
// Function logic
};
- How to implement OAuth authentication in a Node.js/Express application using Passport.js?
- OAuth authentication in a Node.js/Express application can be implemented using the ‘passport’ and ‘passport-oauth’ strategies. This allows users to log in using OAuth providers like Google, Facebook, or GitHub.
Practical Example:
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(new GoogleStrategy({
clientID: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback',
},
(accessToken, refreshToken, profile, done) => {
// Verify user and create session
// ...
}));
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] }));
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/' }),
(req, res) => {
res.redirect('/dashboard');
});
This comprehensive list of Node.js interview questions and practical examples covers a wide range of topics, from basic concepts to advanced features. Keep in mind that this is not an exhaustive list, and candidates may encounter additional topics during interviews. Additionally, the practical examples provided should serve as a starting point, and developers are encouraged to explore and adapt them based on specific project requirements.
Dive into the depths of Node.js expertise! Explore the latest API documentation at Node JS API documentation. Unlock a world of knowledge and elevate your coding prowess!
Explore More: Budget 2024 and Related Articles.
“Nice work!”
Thanks