How to Build a Node.js Static Web Server that Sets MIME Types from a JSON Map
This guide walks through creating a Node.js static web server that intercepts each request, determines the file extension, looks up the appropriate Content‑Type from a JSON mapping, and serves files with correct MIME headers, including handling 404 errors and testing with various resources.
Scenario
A web server delivers documents to browsers and can host static files for worldwide access. While Apache, Nginx, and IIS dominate the market, you can quickly build a simple static server using Node.js and its built‑in modules such as http, url, path and fs.
Implementation
The core idea is to intercept every request, extract the file extension from the URL, and set the corresponding Content‑Type header. Because the number of extensions is large, the mapping is stored in a JSON file ( mime.json) and read with the fs module.
const http = require('http');
const fs = require('fs');
const common = require('./module/common.js');
const path = require('path');
const url = require('url');
http.createServer(function (req, res) {
// 1. Get request path
let pathname = url.parse(req.url).pathname;
// Set root to index.html
pathname = pathname == '/' ? '/index.html' : pathname;
// Get file extension
let extname = path.extname(pathname);
if (pathname != '/favicon.ico') {
fs.readFile('./static' + pathname, (err, data) => {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html;charset="utf-8"'});
res.end('404这个页面不存在');
return;
}
// Get MIME type based on extension
let mime = common.getFileMime(extname);
// Write response header and body
res.writeHead(200, {'Content-Type': '' + mime + ';charset="utf-8"'});
res.end(data);
})
}
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');The server uses a ternary expression to default the root path to /index.html. It reads the requested file from the static directory, returns a 404 page when the file is missing, and writes the appropriate MIME type obtained from common.getFileMime.
const fs = require('fs');
// Synchronous method to read MIME mapping
exports.getFileMime = function (extname) {
var data = fs.readFileSync('./data/mime.json'); // sync read
// Parse JSON and return the MIME for the given extension
let mimeObj = JSON.parse(data.toString());
return mimeObj[extname];
}The mime.json file contains a large object where each key is a file extension (e.g., .html, .js, .png) and each value is the corresponding MIME type such as text/html, application/x‑javascript, image/png, etc.
Testing
Create a static folder in the project and place the compiled front‑end assets there. Then start the server: node app.js Open a browser and navigate to http://localhost:3000. The server serves index.html by default. Accessing http://localhost:3000/js/footer.js returns the JavaScript file with Content‑Type: application/x‑javascript. Requesting a zip file such as http://localhost:3000/static.zip triggers a download because the MIME type is application/zip. All resources are served with the correct headers, demonstrating the static server works as intended.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
