Bird
Raised Fist0
Node.jsframework~10 mins

Response time optimization in Node.js - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a simple HTTP server that responds quickly.

Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end([1]);
});

server.listen(3000);
Drag options to blanks, or click blank then click option'
Aconsole.log('Hello')
Bawait fetch('data')
C'Hello, world!'
Dres.write('Hello')
Attempts:
3 left
💡 Hint
Common Mistakes
Using asynchronous calls inside res.end()
Trying to log instead of sending response
2fill in blank
medium

Complete the code to cache the response data in memory for faster subsequent responses.

Node.js
let cache = null;

const server = http.createServer((req, res) => {
  if (cache) {
    res.end(cache);
  } else {
    const data = 'Cached response';
    cache = [1];
    res.end(data);
  }
});
Drag options to blanks, or click blank then click option'
Anull
Bawait data
Cres.end(data)
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning res.end(data) to cache
Using await incorrectly
3fill in blank
hard

Fix the error in the asynchronous data fetching to improve response time by caching the result.

Node.js
let cache = null;

async function fetchData() {
  if (cache) return cache;
  cache = await [1];
  return cache;
}

const server = http.createServer(async (req, res) => {
  const data = await fetchData();
  res.end(data);
});
Drag options to blanks, or click blank then click option'
Afetch('https://api.example.com/data').then(res => res.text())
Bfetch('https://api.example.com/data')
Cres.end('data')
D'https://api.example.com/data'
Attempts:
3 left
💡 Hint
Common Mistakes
Caching the fetch promise directly
Using string URL instead of fetch call
4fill in blank
hard

Fill both blanks to implement compression middleware for faster response delivery.

Node.js
import express from 'express';
import [1] from 'compression';

const app = express();
app.use([2]());

app.get('/', (req, res) => {
  res.send('Hello with compression');
});
Drag options to blanks, or click blank then click option'
Acompression
Bcors
Dhelmet
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong middleware like cors or helmet
Not calling the middleware function
5fill in blank
hard

Fill all three blanks to implement a simple cache with expiration for API responses.

Node.js
const cache = new Map();
const CACHE_TIME = 60000; // 1 minute

async function getData(key) {
  const cached = cache.get(key);
  if (cached && (Date.now() - cached.timestamp) < [1]) {
    return cached.value;
  }
  const value = await fetch(key).then(res => res.text());
  cache.set(key, { value: [2], timestamp: [3] });
  return value;
}
Drag options to blanks, or click blank then click option'
ACACHE_TIME
Bvalue
CDate.now()
Dkey
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variables for cache values
Not setting timestamp correctly

Practice

(1/5)
1. Which of the following is a common technique to improve response time in a Node.js application?
easy
A. Writing all code synchronously to keep it simple
B. Using only synchronous file system calls
C. Increasing the number of console.log statements
D. Using asynchronous functions to avoid blocking the event loop

Solution

  1. Step 1: Understand Node.js event loop behavior

    Node.js uses an event loop that runs best when tasks are asynchronous, avoiding blocking operations.
  2. Step 2: Identify the impact of async functions

    Using asynchronous functions allows Node.js to handle other requests while waiting, improving response time.
  3. Final Answer:

    Using asynchronous functions to avoid blocking the event loop -> Option D
  4. Quick Check:

    Async = faster response [OK]
Hint: Async code keeps Node.js responsive and fast [OK]
Common Mistakes:
  • Thinking synchronous code is faster
  • Ignoring event loop blocking
  • Believing console.log improves speed
2. Which syntax correctly uses caching middleware in an Express.js app to improve response time?
easy
A. app.use(cacheMiddleware);
B. app.cacheMiddleware();
C. cacheMiddleware(app);
D. app.cache.useMiddleware();

Solution

  1. Step 1: Recall Express middleware usage

    Middleware is added using app.use(middlewareFunction) to apply it to requests.
  2. Step 2: Match correct syntax

    Only app.use(cacheMiddleware); correctly applies the middleware function.
  3. Final Answer:

    app.use(cacheMiddleware); -> Option A
  4. Quick Check:

    Middleware added with app.use() [OK]
Hint: Use app.use() to add middleware in Express [OK]
Common Mistakes:
  • Calling middleware as a method on app
  • Passing app as argument to middleware
  • Using incorrect method names
3. What will be the output response time behavior of this Node.js code snippet?
const express = require('express');
const app = express();

app.get('/data', async (req, res) => {
  const data = await fetchDataFromDb();
  res.send(data);
});

function fetchDataFromDb() {
  return new Promise(resolve => setTimeout(() => resolve('DB Data'), 2000));
}

app.listen(3000);
medium
A. Responds after 2 seconds with 'DB Data'
B. Responds immediately with 'DB Data'
C. Responds immediately with an empty response
D. Throws an error due to missing callback

Solution

  1. Step 1: Analyze fetchDataFromDb function

    This function returns a promise that resolves after 2 seconds with 'DB Data'.
  2. Step 2: Understand async/await in route handler

    The route waits for fetchDataFromDb to finish before sending response, causing 2 seconds delay.
  3. Final Answer:

    Responds after 2 seconds with 'DB Data' -> Option A
  4. Quick Check:

    Await delays response by 2 seconds [OK]
Hint: Await pauses response until promise resolves [OK]
Common Mistakes:
  • Assuming immediate response despite await
  • Confusing async with synchronous code
  • Expecting error without callback in async
4. Identify the bug in this Node.js code that aims to optimize response time using caching:
const cache = {};
app.get('/user/:id', (req, res) => {
  if (cache[req.params.id]) {
    res.send(cache[req.params.id]);
    return;
  }
  const userData = getUserFromDb(req.params.id);
  cache[req.params.id] = userData;
  res.send(userData);
});
medium
A. Cache is cleared after every request
B. res.send is called twice causing error
C. getUserFromDb is asynchronous but used synchronously
D. Cache keys are not strings

Solution

  1. Step 1: Check res.send calls in both branches

    If cache hit, res.send is called, but code continues and calls res.send again after fetching data.
  2. Step 2: Understand Express response behavior

    Calling res.send twice causes an error because response is already sent.
  3. Final Answer:

    res.send is called twice causing error -> Option B
  4. Quick Check:

    Only one res.send per request allowed [OK]
Hint: Return after sending cached response to avoid double send [OK]
Common Mistakes:
  • Ignoring multiple res.send calls
  • Assuming synchronous DB call is fine
  • Not returning after cache hit
5. You want to optimize response time by streaming a large file in Node.js instead of loading it fully into memory. Which code snippet correctly implements this using Express?
hard
A. app.get('/file', (req, res) => { const fs = require('fs'); res.sendFile(fs.readFileSync('large.txt')); });
B. app.get('/file', (req, res) => { const data = fs.readFileSync('large.txt'); res.send(data); });
C. app.get('/file', (req, res) => { const fs = require('fs'); const stream = fs.createReadStream('large.txt'); stream.pipe(res); });
D. app.get('/file', (req, res) => { const data = fs.readFile('large.txt', (err, data) => { res.send(data); }); });

Solution

  1. Step 1: Understand streaming vs full read

    Streaming sends file data in chunks, reducing memory use and improving response time for large files.
  2. Step 2: Identify correct streaming code

    Using fs.createReadStream and piping to res streams data efficiently; other options load full file or use callbacks.
  3. Final Answer:

    app.get('/file', (req, res) => { const fs = require('fs'); const stream = fs.createReadStream('large.txt'); stream.pipe(res); }); -> Option C
  4. Quick Check:

    Stream large files with createReadStream + pipe [OK]
Hint: Use createReadStream and pipe to stream files [OK]
Common Mistakes:
  • Using readFileSync blocks event loop
  • Using readFile loads entire file before response
  • Assuming sendFile streams automatically
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard