Building a Basic HTTP Server with Node.js
To verify Node.js installlation, run the version check command:
node --version
A Node.js application consists of three core components:
- Module imports using
require() - Server creation to handle client requests
- Request/resopnse handlign logic
Here's how to create a simple HTTP server:
const server = require('http');
server.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
res.end('Node.js server response\n');
}).listen(8080);
console.log('Server active on port 8080');
For HTML responses:
const http = require('http');
http.createServer((request, reply) => {
reply.writeHead(200, {'Content-Type': 'text/html'});
reply.write('<meta charset="UTF-8">');
reply.end('<h1>Node.js Server Response</h1>');
}).listen(3000);
Key observations:
- Content-Type header determines response format (text/plain vs text/html)
- Character encoding can be specified in headers or HTML meta tags
- Avoid well-known ports (80, 23) for development servers