Complete the code to create a simple HTTP server that responds quickly.
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);
The server should send a simple string response immediately using res.end() with a string. Using 'Hello, world!' sends a quick response.
Complete the code to cache the response data in memory for faster subsequent responses.
let cache = null;
const server = http.createServer((req, res) => {
if (cache) {
res.end(cache);
} else {
const data = 'Cached response';
cache = [1];
res.end(data);
}
});To cache the response, assign the data string to the cache variable so it can be reused later.
Fix the error in the asynchronous data fetching to improve response time by caching the result.
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);
});The fetch call must be followed by .then(res => res.text()) to get the response body as text before caching it.
Fill both blanks to implement compression middleware for faster response delivery.
import express from 'express'; import [1] from 'compression'; const app = express(); app.use([2]()); app.get('/', (req, res) => { res.send('Hello with compression'); });
To enable compression, import the compression package and use it as middleware with app.use(compression()).
Fill all three blanks to implement a simple cache with expiration for API responses.
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; }
The cache expiration uses CACHE_TIME. The cached value is value, and the timestamp is set to Date.now().