HTTP Server
const http = require('http');\n\nconst server = http.createServer((req, res) => {\n // req is IncomingMessage (Readable stream)\n // res is ServerResponse (Writable stream)\n \n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n message: 'Hello from Node.js',\n method: req.method,\n url: req.url,\n }));\n});\n\nserver.listen(3000, () => {\n console.log('Server listening on port 3000');\n});
Routing
const server = http.createServer((req, res) => {\n const { method, url } = req;\n \n if (url === '/' && method === 'GET') {\n res.end('Home page');\n } else if (url === '/api/users' && method === 'GET') {\n res.end(JSON.stringify([{ id: 1, name: 'Alice' }]));\n } else if (url.match(/^\/api\/users\/(\d+)$/) && method === 'GET') {\n const id = url.match(/^\/api\/users\/(\d+)$/)[1];\n res.end(JSON.stringify({ id: Number(id), name: 'Alice' }));\n } else {\n res.writeHead(404);\n res.end('Not found');\n }\n});
Request Body
let body = '';\nreq.on('data', chunk => body += chunk);\nreq.on('end', () => {\n const data = JSON.parse(body);\n console.log('Received:', data);\n});