Created
May 22, 2020 20:08
-
-
Save kesor/84932396f4af9812caaeb938e8b3e831 to your computer and use it in GitHub Desktop.
Node.js HTTP server to stream static files from the filesystem
This file contains hidden or 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
// based on https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/ | |
const http = require('http'), | |
fs = require('fs') | |
const PORT = process.env.PORT || '8080' | |
function handler(req, res) { | |
const filename = __dirname + req.url | |
let stat | |
try { | |
stat = fs.statSync(filename) | |
} catch (err) { | |
const resJSON = JSON.stringify(err) | |
res.writeHead(404, { | |
'Content-Type': 'application/json', | |
'Content-Length': Buffer.byteLength(resJSON) | |
}) | |
return res.end(resJSON) | |
} | |
const fileSize = stat.size; | |
const fileModTime = stat.mtime; | |
const fileStream = fs.createReadStream(filename, { emitClose: true }) | |
res.writeHead(200, { | |
'Content-Length': fileSize, | |
'Last-Modified': fileModTime, | |
}) | |
fileStream.pipe(res) | |
} | |
http.createServer(handler).listen(PORT) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment