Q1. How do you serve static files (CSS, images) in Node.js?
Create a handler that reads files from a public directory. Example:
if (req.url.startsWith('/static/')) {
const filePath = path.join(__dirname, 'public', req.url.slice(8));
fs.readFile(filePath, (err, data) => {
if (err) {
res.statusCode = 404;
res.end();
} else {
res.end(data);
}
});
}
Set proper Content-Type based on extension.Q2. How do you determine the MIME type for static files?
Map file extensions to MIME types. Example:
const mimeTypes = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.json': 'application/json'
};
const ext = path.extname(filePath);
const contentType = mimeTypes[ext] || 'application/octet-stream';
Q3. How do you handle large static files efficiently?
Use streams instead of reading entire files into memory. Example:
const stream = fs.createReadStream(filePath);
stream.pipe(res);
Handle errors on the stream. This is memory-efficient for large files. Also set appropriate caching headers for performance.Q4. How do you implement caching for static files?
Set Cache-Control headers. Example:
res.setHeader('Cache-Control', 'public, max-age=86400'); // 1 day
You can also use ETag for validation: generate a hash of the file and set res.setHeader('ETag', etag). Check If-None-Match header to return 304 Not Modified.Q5. What security considerations for static file serving?
Prevent directory traversal attacks by validating paths: ensure resolved path is within public directory. Example:
const resolvedPath = path.resolve(publicDir, filePath);
if (!resolvedPath.startsWith(publicDir)) {
return 403;
}
Also set appropriate headers like X-Content-Type-Options: nosniff to prevent MIME sniffing.