Q1. How do you serve an HTML file using Node.js?
Read the HTML file with fs and send it with proper Content-Type. Example:
const fs = require('fs'); const http = require('http'); http.createServer((req, res) => { fs.readFile('index.html', (err, data) => { if (err) { res.statusCode = 500; res.end('Error'); } else { res.setHeader('Content-Type', 'text/html'); res.end(data); } }); }).listen(3000);Q2. How do you serve HTML with dynamic content?
Read an HTML template, then replace placeholders. Example:
fs.readFile('template.html', 'utf8', (err, template) => { const html = template.replace('{{name}}', 'John'); res.setHeader('Content-Type', 'text/html'); res.end(html); });. For complex templates, consider using templating engines like EJS or Handlebars.Q3. How do you handle 404 for missing HTML files?
Check if file exists before reading, or handle the ENOENT error from fs.readFile. Example:
fs.readFile('page.html', (err, data) => { if (err && err.code === 'ENOENT') { res.statusCode = 404; res.end('404 Not Found'); } else if (err) { res.statusCode = 500; } else { res.end(data); } });Q4. What Content-Type should you use for HTML?
For HTML files, set Content-Type to 'text/html'. You can also include charset: 'text/html; charset=utf-8'. This tells the browser to interpret the response as HTML. For other file types, use appropriate MIME types: 'text/css', 'application/javascript', etc.
Q5. How do you serve HTML efficiently for many requests?
For static HTML files, use caching headers and consider reading files once and caching in memory. For dynamic HTML, use streaming or template caching. In production, use a reverse proxy like Nginx to serve static files, and use clustering or load balancing for your Node.js server.
