Serve an HTML page using Node.js
By Flavio
Published · Updated
Tagged: Node.js
Learn how to serve an index.html page using Node.js with no dependencies, using the http module and piping fs.createReadStream() to the response.
I had the need to serve an HTML page from a Node.js server, and this is the simplest code that does the trick:
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html' })
fs.createReadStream('index.html').pipe(res)
})
server.listen(process.env.PORT || 3000)
No dependencies needed.
Add this to an app.js file, then create an index.html page, and run node app.js. Open http://localhost:3000 and you’ll see your page.
Notice that the above code does not provide support for serving static assets, it will just serve the index.html page.
It’s fine for a quick test, but it has a few problems you’ll hit soon.
Problems with the simple version
The path depends on where you run it. 'index.html' is resolved from the folder you run node from, not from the folder of app.js. If you run node project/app.js from the parent folder, Node can’t find the file.
A missing file crashes the server. When createReadStream() can’t open the file, it emits an error event. Nothing listens for it, so the whole Node process exits with ENOENT: no such file or directory. The first request kills the server.
Every URL returns the page. /about, /whatever and /favicon.ico (which browsers ask for on their own) all get index.html with a 200 status.
No charset. Without charset=utf-8 in the Content-Type header, the browser has to guess the encoding. Add <meta charset="utf-8"> in the HTML or send it in the header, or accented letters and emoji can show up broken.
A better version
This version fixes all four problems:
import http from 'node:http'
import fs from 'node:fs/promises'
import path from 'node:path'
const file = path.join(import.meta.dirname, 'index.html')
const server = http.createServer(async (req, res) => {
const { pathname } = new URL(req.url, 'http://localhost')
if (pathname !== '/') {
res.writeHead(404, { 'content-type': 'text/plain' })
res.end('Not found')
return
}
try {
const html = await fs.readFile(file)
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
res.end(html)
} catch (err) {
console.error(err)
res.writeHead(500, { 'content-type': 'text/plain' })
res.end('Could not read index.html')
}
})
const port = process.env.PORT || 3000
server.listen(port, () => {
console.log(`Listening on http://localhost:${port}`)
})
It uses ES modules, so either name the file app.mjs, or add "type": "module" to your package.json.
What changed:
import.meta.dirnameis the folder of the current file, so the path toindex.htmlworks from anywhere. It’s available since Node 20.11. In a CommonJS file use__dirnameinstead.- I read
req.urlwithnew URL()and only check thepathname. This way/?ref=newsletterstill serves the page, and everything else gets a404. fs.readFile()is inside atry/catch. If the file is missing, the user gets a500error and the server keeps running.
readFile() loads the whole file in memory. For an HTML page that’s perfect. For big files, like videos, stick to streams: pipeline() from node:stream/promises pipes a read stream into res and gives you the errors in one place.
Changes to the HTML show up right away
The file is read again on every request, so you can edit index.html and just reload the browser.
If you change app.js, run it with node --watch app.js. Node restarts the server every time you save the file. Watch mode is stable since Node 22. It watches your JS files and what they import, not the HTML files, but with this setup you don’t need that.
Serving more than one page
To serve a few pages, map each URL to a file:
import http from 'node:http'
import fs from 'node:fs/promises'
import path from 'node:path'
const pages = {
'/': 'index.html',
'/about': 'about.html',
}
const server = http.createServer(async (req, res) => {
const { pathname } = new URL(req.url, 'http://localhost')
const page = pages[pathname]
if (!page) {
res.writeHead(404, { 'content-type': 'text/plain' })
res.end('Not found')
return
}
try {
const html = await fs.readFile(path.join(import.meta.dirname, page))
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
res.end(html)
} catch (err) {
console.error(err)
res.writeHead(500, { 'content-type': 'text/plain' })
res.end('Server error')
}
})
server.listen(process.env.PORT || 3000)
I use a list of allowed pages on purpose. Don’t build the file path straight from req.url: a request for /../../some-secret-file could read files outside your folder.
Once your page loads CSS, JavaScript and images, you need to serve all those files too, each with the right Content-Type. At that point I’d use Express and its built-in static middleware, see serving static assets with Express.
Want me to talk about your product? You can sponsor this site.
Related posts about node: