Performance: Why understanding res matters
Understanding the response object (res) affects how quickly and efficiently the server sends data to the browser, impacting page load speed and user experience.
app.get('/data', async (req, res) => { // Offload heavy processing asynchronously const data = await heavyComputationAsync(); res.send(data); });
app.get('/data', (req, res) => {
// Doing heavy processing before sending response
const data = heavyComputation();
res.send(data);
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking synchronous processing before res.send | N/A | N/A | Delays initial paint | [X] Bad |
| Asynchronous processing with prompt res.send | N/A | N/A | Faster initial paint | [OK] Good |
res object in Express?res in Expressres object represents the response that the server sends back to the client after processing a request.res from other objectsreq object handles incoming requests, while res controls what is sent back, such as text, JSON, or files.res sends responses [OK]res in Express?res.json() method to send JSON data properly formatted to the client.res.json() is the correct method name; others like sendJson or sendJSON do not exist.res.json() for JSON [OK]app.get('/hello', (req, res) => {
res.status(200).send('Welcome!');
});res.status(200)res.send('Welcome!')app.get('/data', (req, res) => {
res.send('Data loaded');
res.json({ success: true });
});res.send() sends a response, the connection closes and no further response can be sent.res.json() after res.send() tries to send a second response, causing an error.report.pdf to the client using res. Which code snippet correctly achieves this in Express?res.sendFile() sends a file as response, but requires an absolute path or root option; res.download() prompts the client to download the file.res.download('report.pdf') sends the file with headers to trigger download, which is usually desired for files like PDFs.Pass the test and this pattern moves unknown