Skip to content

Instantly share code, notes, and snippets.

@vanyle
Created August 20, 2021 19:55
Show Gist options
  • Save vanyle/e4c822c80797756c5e7845fb167e725c to your computer and use it in GitHub Desktop.
Save vanyle/e4c822c80797756c5e7845fb167e725c to your computer and use it in GitHub Desktop.
A minimal example of a node server able to serve all files inside a directory. It uses no dependencies like express.
// 1. No dependencies.
// 2. Provide files in current directory and childrens
// 3. Tiny.
// Useful if you need to quickly setup a webserver for testing or prototyping.
const port = 80;
const http = require('http');
const fs = require('fs');
const path = require('path');
let server = http.createServer((req,res) => {
let p = req.url;
p = "."+path.normalize(p);
if(fs.existsSync(p)){
let f = fs.statSync(p);
if(f.isFile()){
let s = fs.createReadStream(p);
s.on("data", (d) => {
res.write(d);
});
s.on("end", () => {
res.end();
});
}else{
res.write(`404: ${p}`);
res.end();
}
}else{
res.write(`404: ${p}`);
res.end();
}
});
server.listen(port,() => {
console.log(`http://localhost:${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment