Skip to content

Instantly share code, notes, and snippets.

@darlanalves
Created August 31, 2023 12:28
Show Gist options
  • Save darlanalves/358e72f6d4b621c7af4991a88567df5a to your computer and use it in GitHub Desktop.
Save darlanalves/358e72f6d4b621c7af4991a88567df5a to your computer and use it in GitHub Desktop.
Http server for local development in Node.js
#!/usr/bin/env node
// Save this file somewhere and make it executable: `chmod +x http.mjs`, then add to $PATH.
// Just run `http.mjs` from any folder to serve the files.
import { createServer } from 'node:http';
import { join } from 'node:path';
import { createReadStream, existsSync } from 'node:fs';
import process from 'node:process';
const cwd = join(process.cwd(), process.argv[2] || '');
process.chdir(cwd);
const port = Number(process.env.PORT || 3000);
const getPath = (r) => r.url === '/' ? 'index.html' : r.url.slice(1);
createServer((req, res) => {
const p = join(cwd, getPath(req));
if (existsSync(p)) {
createReadStream(p).pipe(res);
return;
}
res.writeHead(404).end('Not found: ' + req.url);
}).listen(port, () => console.log(`${cwd}\nListening on http://localhost:${port}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment