Home / Node JS / Coding interview questions related to Node.js and Express.js, along with their answers

Coding interview questions related to Node.js and Express.js, along with their answers

1. What is the purpose of app.use() in Express.js?

Answer:

In Express.js, app.use() is a method used to add middleware to your application. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. They can modify the request and response objects, end the request-response cycle, or call the next middleware function in the stack.

Example:

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

// Middleware to log request details
app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next(); // Pass control to the next middleware
});

2. How can you handle errors in an Express.js application?

Answer:

In Express.js, you handle errors by defining an error-handling middleware. Error-handling middleware functions have four arguments: err, req, res, and next. They are defined after all other middleware and routes.

Example:

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

// Some route that may cause an error
app.get('/error', (req, res, next) => {
    try {
        throw new Error('Something went wrong!');
    } catch (err) {
        next(err); // Pass errors to the error-handling middleware
    }
});

// Error-handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

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

3. How do you set up a basic route in Express.js?

Answer:

To set up a basic route in Express.js, use the app.get(), app.post(), app.put(), or app.delete() methods, depending on the HTTP method you want to handle. Each of these methods takes a route path and a callback function to handle requests to that path.

Example:

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

// Handle GET request to the root URL
app.get('/', (req, res) => {
    res.send('Hello, world!');
});

// Handle POST request to /submit
app.post('/submit', (req, res) => {
    res.send('Form submitted!');
});

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

4. How do you parse JSON bodies in Express.js?

Answer:

To parse JSON bodies in Express.js, you use the express.json() middleware. This middleware parses incoming requests with JSON payloads and makes the parsed data available in req.body.

Example:

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

// Middleware to parse JSON bodies
app.use(express.json());

app.post('/data', (req, res) => {
    console.log(req.body); // Parsed JSON data
    res.send('Data received');
});

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

5. How do you serve static files in Express.js?

Answer:

To serve static files in Express.js, use the express.static() middleware. You specify a directory from which static files should be served.

Example:

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

// Serve static files from the "public" directory
app.use(express.static(path.join(__dirname, 'public')));

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

In this example, if you place files in the public directory, they can be accessed directly via the URL path.

6. How can you handle different HTTP methods for the same route?

Answer:

You can handle different HTTP methods for the same route by using app.get(), app.post(), app.put(), app.delete(), etc., for the specific methods you want to handle.

Example:

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

// Handle GET request
app.get('/resource', (req, res) => {
    res.send('GET request to /resource');
});

// Handle POST request
app.post('/resource', (req, res) => {
    res.send('POST request to /resource');
});

// Handle PUT request
app.put('/resource', (req, res) => {
    res.send('PUT request to /resource');
});

// Handle DELETE request
app.delete('/resource', (req, res) => {
    res.send('DELETE request to /resource');
});

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

7. How do you perform asynchronous operations in Express.js?

Answer:

You can perform asynchronous operations in Express.js by using async functions and await syntax. This helps manage asynchronous code more cleanly compared to traditional callbacks or promises.

Example:

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

// Example asynchronous operation
app.get('/data', async (req, res) => {
    try {
        const data = await someAsyncFunction(); // Assume this is an async function
        res.json(data);
    } catch (err) {
        res.status(500).send('Server error');
    }
});

async function someAsyncFunction() {
    // Simulate an async operation, e.g., fetching data from a database
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({ message: 'Data fetched' });
        }, 1000);
    });
}

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

8. How do you handle query parameters in Express.js?

Answer:

Query parameters in Express.js are accessed through req.query. Query parameters are typically included in the URL after a ?, such as /search?term=example.

Example:

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

app.get('/search', (req, res) => {
    const term = req.query.term; // Access the 'term' query parameter
    res.send(`Search term: ${term}`);
});

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

9. Display Hostname and Platform Details

File: systemInfo.js

const os = require('os');

console.log('Hostname:', os.hostname());
console.log('Platform:', os.platform());
console.log('Architecture:', os.arch());

Run Command: node systemInfo.js

10. Display Text in Colors

File: coloredText.js

const colors = require('colors');

console.log('This is red text'.red);
console.log('This is green text'.green);
console.log('This is blue text'.blue);
console.log('This is yellow text'.yellow);

Setup: npm install colors

Run Command: node coloredText.js

11. User-defined Math Module

File: math.js (module)

// math.js
module.exports = {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
    multiply: (a, b) => a * b,
    divide: (a, b) => b !== 0 ? a / b : 'Cannot divide by zero'
};

File: useMath.js (usage)

const math = require('./math');

const a = 10;
const b = 5;

console.log(`Addition: ${a} + ${b} = ${math.add(a, b)}`);
console.log(`Subtraction: ${a} - ${b} = ${math.subtract(a, b)}`);
console.log(`Multiplication: ${a} * ${b} = ${math.multiply(a, b)}`);
console.log(`Division: ${a} / ${b} = ${math.divide(a, b)}`);

Run Command: node useMath.js

12. Display Message with Delay

File: delayedMessage.js

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function showMessage() {
    console.log('Message will appear after 3 seconds...');
    await delay(3000);
    console.log('Here is the delayed message!');
}

showMessage();

Run Command: node delayedMessage.js

12. Display Hostname and Platform Details via Express

File: server.js

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

const app = express();
const port = 3000;

app.get('/system-info', (req, res) => {
    res.json({
        hostname: os.hostname(),
        platform: os.platform(),
        architecture: os.arch()
    });
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});

Run Command: node server.js

Access: http://localhost:3000/system-info

13. Display Text in Colors via Express

File: coloredTextServer.js

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

const app = express();
const port = 3001;

app.get('/colored-text', (req, res) => {
    res.send(`
        <p style="color: red;">This is red text</p>
        <p style="color: green;">This is green text</p>
        <p style="color: blue;">This is blue text</p>
        <p style="color: yellow;">This is yellow text</p>
    `);
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});

Run Command: node coloredTextServer.js

Access: http://localhost:3001/colored-text

14. Math Module and Use with Express

File: mathServer.js

const express = require('express');
const bodyParser = require('body-parser');
const math = require('./math');

const app = express();
const port = 3002;

app.use(bodyParser.json());

app.post('/math', (req, res) => {
    const { operation, a, b } = req.body;

    if (typeof a !== 'number' || typeof b !== 'number') {
        return res.status(400).json({ error: 'Invalid input' });
    }

    let result;

    switch (operation) {
        case 'add':
            result = math.add(a, b);
            break;
        case 'subtract':
            result = math.subtract(a, b);
            break;
        case 'multiply':
            result = math.multiply(a, b);
            break;
        case 'divide':
            result = math.divide(a, b);
            break;
        default:
            return res.status(400).json({ error: 'Invalid operation' });
    }

    res.json({ result });
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});

Run Command: node mathServer.js

Testing: Use Postman or curl for requests:

curl -X POST http://localhost:3002/math -H "Content-Type: application/json" -d '{"operation":"add","a":10,"b":5}'

15. Display Message with Delay via Express

File: delayedMessageServer.js

const express = require('express');

const app = express();
const port = 3003;

app.get('/delayed-message', (req, res) => {
    setTimeout(() => {
        res.send('Here is the delayed message!');
    }, 3000);
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});

Run Command: node delayedMessageServer.js

Access: http://localhost:3003/delayed-message

About Sushil Kumar

Leave a Reply

Your email address will not be published. Required fields are marked *