Run npx https://gist.github.com/Dammmien/1c94aebefb7d733e4f6d3cc9c11b978b 8000
in a folder
Last active
May 24, 2019 16:46
-
-
Save Dammmien/1c94aebefb7d733e4f6d3cc9c11b978b to your computer and use it in GitHub Desktop.
Minimalist static file server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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