Tiny static server
A tiny development web server for static content
Motivation
There are many other static dev servers out there, for example you can try with
python -m http.server
But you need to have Python installed.
If you are using Node.JS, you can try with static-server or serve.
But you need to install an npm dependency.
Instead you can just copy paste this tiny script below.
If you name it server.js and place it in your working folder, then you can launch it with just
npm start
No need to edit your package.json file.
Otherwise just launch it with node server.
Show me the code
The server will automatically open your default browser.
import { exec } from 'node:child_process'
import { createServer } from 'node:http'
import { readFile } from 'node:fs'
import os from 'node:os'
const server = createServer((req, res) => {
// Ignore URLs like Chrome DevTools
// /.well-known/appspecific/com.chrome.devtools.json
if (req.url.startsWith('/.well-known'))
return
// Assuming (req.method == 'GET')
readFile(
`.${req.url == '/' ? '/index.html' : req.url}`,
(err, data) => err ? res.writeHead(400).end() : res.end(data)
)
})
server.listen(process.env.PORT, () => {
const baseUrl = `http://localhost:${server.address().port}`
// Open default browser.
switch(os.platform()) {
case 'darwin': exec(`open ${baseUrl}`)
case 'linux': exec(`xdg-open ${baseUrl}`)
case 'win32': exec(`start ${baseUrl}`)
default: console.info(`Server started on ${baseUrl}`)
}
})