Performance: Why building HTTP servers matters
This concept affects how quickly a web page or API responds to user requests, impacting the initial load time and interaction speed.
Jump into concepts and practice - no test required
import http from 'node:http'; import { Worker } from 'node:worker_threads'; const server = http.createServer((req, res) => { const worker = new Worker(new URL('./heavyTask.js', import.meta.url)); worker.on('message', () => res.end('Hello World')); }); server.listen(3000);
const http = require('http'); http.createServer((req, res) => { // Synchronous heavy computation for(let i = 0; i < 1e9; i++) {} res.end('Hello World'); }).listen(3000);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking synchronous server code | N/A | N/A | Delays initial paint | [X] Bad |
| Non-blocking asynchronous server with workers | N/A | N/A | Enables fast initial paint | [OK] Good |
import to load modules, not require.http.createServer with res.end() is correct; res.send() is not a Node.js method.import http from 'http';
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Welcome!');
});
server.listen(3000);import http from 'http';
const server = http.createServer((req, res) => {
res.write('Hello');
res.write('World');
res.end();
});
server.listen(3000);