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 the script below in a server.js file.
Show me the code
import { exec } from 'node:child_process'
import { createServer } from 'node:http'
import { readFile } from 'node:fs'
import { networkInterfaces, platform } from 'node:os'
const port = process.env.PORT
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('Not found') : res.end(data)
)
})
server.listen(port, () => {
const serverPort = server.address().port
const localUrl = `http://localhost:${serverPort}`
let externalUrl = localUrl
// Look for IPv4 net interface.
const nets = networkInterfaces()
for (const name of Object.keys(nets))
for (const net of nets[name])
if (net.family === 'IPv4' && !net.internal) {
externalUrl = new URL(`http://${net.address}:${serverPort}`)
break
}
// Open default browser.
switch(platform()) {
case 'darwin': exec(`open ${localUrl}`)
case 'linux': exec(`xdg-open ${localUrl}`)
case 'win32': exec(`start ${localUrl}`)
default: console.info(`Server started on ${externalUrl}`)
}
})
How to launch
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.
If you have not package.json just launch it with node server.
Environment variable
PORT is supported. If not provided it will use a random port.
So to choose a port, you can launch it with
PORT=1234 node server.js
In case you want to add a default port, for instance 3000, just change this row
- const port = process.env.PORT
+ const port = process.env.PORT ?? 3000
If an IPv4 address is available, other clients in your local network can connect using the URL that is printed once the server is started.
For example, you will see
node server.js
Server started on http://192.168.1.52:53774/
Your default browser will open automatically. The URL used locally will be always
localhost to facilitate development tasks.