Q1. How do you create a basic HTTP server in Node.js?
Use the http module:
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World'); }); server.listen(3000, () => console.log('Server running'));. This creates a server that responds to all requests with "Hello World".Q2. What does http.createServer return?
It returns an instance of http.Server, which is an EventEmitter. You can listen for events like 'request', 'connection', etc. The server object has methods like .listen() to start listening, .close() to stop, and properties like .maxHeadersCount. The callback passed to createServer is automatically attached to the 'request' event.
Q3. How do you handle different URLs in a raw HTTP server?
In the request handler, check req.url. Example:
if (req.url === '/') { res.end('Home'); } else if (req.url === '/about') { res.end('About'); } else { res.statusCode = 404; res.end('Not Found'); }. For more complex routing, you'd use conditional logic or switch statements.Q4. How do you set the HTTP status code and headers?
Use res.statusCode = 404 to set status. For headers, use res.setHeader('Content-Type', 'text/html') or res.writeHead(200, {'Content-Type': 'text/html'}) which sets both status and headers. Headers must be set before writing the body. Multiple headers can be set.
Q5. How do you get the server to listen on a specific port?
server.listen(port, [hostname], [backlog], [callback]). Example:
server.listen(3000, '127.0.0.1', () => { console.log('Server bound'); }); If hostname is omitted, the server accepts connections on any IPv4 address. The callback runs when server starts listening.