Skip to content

Instantly share code, notes, and snippets.

@Dammmien
Last active May 24, 2019 16:46
Show Gist options
  • Save Dammmien/1c94aebefb7d733e4f6d3cc9c11b978b to your computer and use it in GitHub Desktop.
Save Dammmien/1c94aebefb7d733e4f6d3cc9c11b978b to your computer and use it in GitHub Desktop.
Minimalist static file server

Run npx https://gist.github.com/Dammmien/1c94aebefb7d733e4f6d3cc9c11b978b 8000 in a folder

#!/usr/bin/env node
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const [ runtime, scriptName, port = 3000, folder = process.cwd() ] = process.argv;
class Server {
constructor(port) {
this.httpServer = http.createServer(this.onRequest.bind(this)).listen(port);
console.log(`Server listening on port ${port} in ${folder}`);
}
getContentType(pathname) {
return {
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css'
}[path.parse(pathname).ext] || 'text/plain'
}
sendError(res, filePath, message) {
res.writeHead(404, 'Not Found', {
'Content-Type': this.getContentType(filePath),
'Content-Length': Buffer.byteLength(message)
});
res.end(message);
}
sendFile(filePath, stat, res) {
res.writeHead(200, 'OK', {
'Content-Type': this.getContentType(filePath),
'Content-Length': stat.size
});
fs.createReadStream(filePath).pipe(res);
}
onRequest(req, res) {
const filePath = `${folder}${url.parse(req.url).pathname}`;
try {
const stat = fs.statSync(filePath);
if (stat.isDirectory()) return this.checkFile(filePath += 'index.html');
this.sendFile(filePath, stat, res)
} catch (err) {
this.sendError(res, filePath, `No such file or directory: ${filePath}!`);
}
}
};
const server = new Server(port);
{
"name": "static-file-server",
"version": "0.0.0",
"bin": "./index.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment