Performance: Creating a basic HTTP server
This concept affects the initial server response time and how quickly the browser receives the first byte of content.
Jump into concepts and practice - no test required
import http from 'http'; const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/html'}); function writeLines(i) { let ok = true; while (i < 10000 && ok) { ok = res.write(`<p>Line ${i}</p>`); i++; } if (i < 10000) { res.once('drain', () => writeLines(i)); } else { res.end(); } } writeLines(0); }); server.listen(3000);
import http from 'http'; const server = http.createServer((req, res) => { let html = ''; for (let i = 0; i < 10000; i++) { html += '<p>Line ' + i + '</p>'; } res.writeHead(200, {'Content-Type': 'text/html'}); res.end(html); }); server.listen(3000);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous large string build before response | N/A (server-side) | N/A | N/A | [X] Bad |
| Streaming response in chunks | N/A (server-side) | N/A | N/A | [OK] Good |
http.createServer() function do in Node.js?http.createServer()listen().server.listen(3000); starts the server on port 3000.const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World');
});
server.listen(4000);const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome');
res.end();
});
server.listen(8080)
console.log('Server running on port 8080');{"status":"ok"} and sets the correct header. Which code snippet correctly does this?JSON.stringify() to convert the object to a JSON string before sending with res.end().