Skip to main content

Command Palette

Search for a command to run...

Nodejs interview series Part-2

Updated
8 min read
Nodejs interview series Part-2
T

I'm a full-stack software developer creating open-source projects and writing about modern JavaScript client-side and server-side. Working remotely from India.

1. What is middleware in the context of Express.js? How is it used?

Middleware in Express.js refers to functions that have access to the request, response, and the next middleware function in the application’s request-response cycle. It is used to perform tasks such as logging, authentication, and error handling.

Example: Logging Middleware

const express = require('express');  
const app = express();  

// Logging middleware  
app.use((req, res, next) => {  
  console.log('Request received:', req.method, req.url);  
  next(); // Pass control to the next middleware  
});  

// Route handler  
app.get('/', (req, res) => {  
  res.send('Hello, Express!');  
});  

app.listen(3000, () => {  
  console.log('Server is running on port 3000');  
});

2. Explain the concept of streams in Node.js. When would you use them?

Streams in Node.js are objects that allow reading or writing data continuously. They are especially useful when working with large amounts of data, as they enable processing data in chunks, reducing memory consumption and improving performance.

Example: Reading from a Stream

const fs = require('fs');  

const stream = fs.createReadStream('example.txt', 'utf8');  
stream.on('data', chunk => {  
  console.log('Received chunk:', chunk);  
});  
stream.on('end', () => {  
  console.log('Stream ended');  
});

3. How does error handling differ in synchronous and asynchronous code in Node.js?

In synchronous code, errors are handled using try-catch blocks, where exceptions are caught synchronously. In asynchronous code, errors are typically handled using callback conventions, where the first argument of the callback function represents an error object.

Example: Synchronous Error Handling

try {  
  // Synchronous code that may throw an error  
} catch (error) {  
  console.error('Error:', error);  
}

**Example:** Asynchronous Error Handling

fs.readFile('example.txt', 'utf8', (err, data) => {  
  if (err) {  
    console.error('Error reading file:', err);  
    return;  
  }  
  console.log('File content:', data);  
});

4. How do you debug a Node.js application?

Node.js provides built-in debugging support through the Node Inspector tool. Additionally, developers can use console.log statements, the debugger keyword, or third-party debugging tools like Visual Studio Code for debugging Node.js applications.

Example: Using console.log for Debugging

const variable = 'test';  
console.log('Variable:', variable);

5. Explain the concept of RESTful APIs and how they are implemented in Node.js.

RESTful APIs are web APIs that adhere to the principles of Representational State Transfer (REST). They use standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources. In Node.js, RESTful APIs can be implemented using frameworks like Express.js.

Example: Creating a RESTful API with Express.js

const express = require('express');  
const app = express();  

// Route handler for GET request to '/users'  
app.get('/users', (req, res) => {  
  // Logic to retrieve users from the database  
  res.json({ users: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] });  
});  

app.listen(3000, () => {  
  console.log('Server is running on port 3000');  
});

6. What are some security best practices when developing a Node.js application?

When developing Node.js applications, it’s essential to follow security best practices such as validating input data, using parameterized queries to prevent SQL injection, implementing authentication and authorization mechanisms, and regularly updating dependencies to patch security vulnerabilities.

Example: Input Data Validation

const express = require('express');  
const Joi = require('joi'); // Validation library  

const app = express();  

// Middleware for validating request body  
app.use(express.json());  

// Route handler for POST request to '/login'  
app.post('/login', (req, res) => {  
  // Validate request body  
  const schema = Joi.object({  
    username: Joi.string().alphanum().min(3).max(30).required(),  
    password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(),  
  });  
  const { error } = schema.validate(req.body);  
  if (error) {  
    return res.status(400).send(error.details[0].message);  
  }  
  // Continue with login logic  
});  

app.listen(3000, () => {  
  console.log('Server is running on port 3000');  
});

7. How do you handle database operations in a Node.js application?

In Node.js applications, database operations are typically performed using database drivers or ORMs (Object-Relational Mappers) such as Sequelize or Mongoose. These libraries provide APIs for connecting to databases, executing queries, and interacting with database models.

Example: Database Operation with Sequelize

const { Sequelize, DataTypes } = require('sequelize');  

// Initialize Sequelize  
const sequelize = new Sequelize('sqlite::memory:');  

// Define a model  
const User = sequelize.define('User', {  
  username: DataTypes.STRING,  
  email: DataTypes.STRING,  
});  

// Create a new user  
async function createUser(username, email) {  
  await User.create({ username, email });  
}  

createUser('john_doe', 'john@example.com');

8. What is the role of the process object in Node.js? Give examples of its usage.

The process object in Node.js provides information and control over the Node.js process. It allows access to environment variables, command-line arguments, and provides methods for exiting the process or listening for signals.

Example: Accessing Command-Line Arguments

console.log('Arguments:', process.argv);

9. Explain the difference between setImmediate(), setTimeout(), and process.nextTick() in Node.js.

  • setImmediate() schedules a callback function to be executed in the next iteration of the event loop.
  • setTimeout() schedules a callback function to be executed after a specified delay.
  • process.nextTick() schedules a callback function to be executed immediately after the current operation completes, before the event loop continues.

  • What is session management in Express.js? How can it be implemented?

Session management in Express.js involves maintaining user sessions and managing session data across multiple requests. It can be implemented using session middleware like express-session and storing session data in memory, a database, or a session store like Redis.

Example: Implementing Session Management with express-session

const express = require('express');  
const session = require('express-session');  
const app = express();  

// Session middleware  
app.use(session({  
  secret: 'secret-key',  
  resave: false,  
  saveUninitialized: true,  
}));  

// Route handler for setting session data  
app.get('/set-session', (req, res) => {  
  req.session.username = 'john_doe';  
  res.send('Session data set');  
});  

// Route handler for getting session data  
app.get('/get-session', (req, res) => {  
  const username = req.session.username || 'Guest';  
  res.send('Session data: ' + username);  
});  

app.listen(3000, () => {  
  console.log('Server is running on port 3000');  
});

11. How do you handle file uploads in an Express.js application?

File uploads in an Express.js application can be handled using middleware like multer. Multer provides easy handling of multipart/form-data, which is typically used for file uploads.

Example: Handling File Uploads with Multer

const express = require('express');  
const multer = require('multer');  
const app = express();  

// Multer middleware for handling file uploads  
const upload = multer({ dest: 'uploads/' });  

// Route handler for file upload  
app.post('/upload', upload.single('file'), (req, res) => {  
  // File uploaded successfully  
  res.send('File uploaded');  
});  

app.listen(3000, () => {  
  console.log('Server is running on port 3000');  
});

12. What are the differences between require() and import in Node.js?

require() is a CommonJS module system function used to import modules in Node.js, while import is an ES6 feature used for importing modules in modern JavaScript environments. Here's an example of require():

const fs = require('fs');

And here’s an example of `import`:

import fs from 'fs';

13. What is authentication? How is it implemented in Node.js applications?

Authentication is the process of verifying the identity of a user. In Node.js applications, authentication can be implemented using techniques such as username/password authentication, JSON Web Tokens (JWT), OAuth, and session-based authentication. Here’s a basic example of session-based authentication:

app.post('/login', (req, res) => {  
  // Validate username and password  
  if (req.body.username === 'user' && req.body.password === 'password') {  
    // Set authenticated session  
    req.session.authenticated = true;  
    res.send('Login successful');  
  } else {  
    res.status(401).send('Invalid username or password');  
  }  
});

14. Explain the concept of middleware chaining in Express.js.

Middleware chaining in Express.js involves using multiple middleware functions sequentially in the request-response cycle. Each middleware function can perform its specific task and pass control to the next middleware using the next() function. Here's an example:

app.use((req, res, next) => {  
  console.log('Middleware 1');  
  next();  
});  

app.use((req, res, next) => {  
  console.log('Middleware 2');  
  next();  
});

15. How do you handle CORS (Cross-Origin Resource Sharing) in a Node.js application?

CORS in a Node.js application can be handled using middleware like cors. Here's an example:

const cors = require('cors');  

app.use(cors());

This allows requests from any origin by default. You can also configure CORS options to restrict origins, methods, and headers.

16. What are the advantages of using a templating engine like EJS or Handlebars in Express.js?

Templating engines like EJS or Handlebars allow developers to generate dynamic HTML content on the server-side by embedding JavaScript code into HTML templates. They simplify the process of building dynamic web pages and separating presentation logic from business logic. Here’s an example of using EJS:

app.set('view engine', 'ejs');

17. How do you deploy a Node.js application to a production server?

Node.js applications can be deployed to production servers using various deployment strategies such as manual deployment, continuous integration/continuous deployment (CI/CD) pipelines, containerization with Docker, and cloud platforms like AWS, Heroku, or Azure.

18. Explain the purpose of the express.static() middleware in Express.js.

The express.static() middleware in Express.js is used to serve static files such as images, CSS, JavaScript, and other assets from a specified directory. Here's an example:

app.use(express.static('public'));

This serves files from the public directory relative to the application root.

19. What are route parameters in Express.js? How do you access them?

Route parameters in Express.js are placeholders in the route definition that capture values from the URL. They are specified in the route path using colon syntax (:) and can be accessed in route handlers using req.params. Here's an example:

app.get('/users/:userId', (req, res) => {  
  const userId = req.params.userId;  
  // Use userId in the route handler  
});

20. How do you handle sessions and cookies in an Express.js application?

Sessions and cookies in an Express.js application can be handled using middleware like express-session and cookie-parser. Here's an example of setting up sessions:

const session = require('express-session');  
const cookieParser = require('cookie-parser');  

app.use(cookieParser());  
app.use(session({ secret: 'secret-key', resave: false, saveUninitialized: true }));

Conclusion:

Mastering intermediate-level concepts in Node.js is essential for excelling in interviews and building robust applications. In this article, we’ve covered various topics including middleware, streams, error handling, RESTful APIs, security best practices, database operations, and more. Armed with these insights and examples, you’re well-equipped to tackle advanced Node.js interview questions and take your skills to the next level.

Continue your Node.js interview preparation journey with our comprehensive guides:

Stay tuned for more insightful content and happy coding!