Created
July 29, 2020 09:44
-
-
Save bhubr/31fd1dff2f218b57d468cda9a563d0bf to your computer and use it in GitHub Desktop.
Static file server / pure Node.js
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
// https://stackoverflow.com/questions/7268033/basic-static-file-server-in-nodejs | |
const http = require('http') | |
const url = require('url') | |
const fs = require('fs') | |
const { join, extname } = require('path') | |
const { promisify } = require('util') | |
const statAsync = promisify(fs.stat) | |
const fileExists = async file => statAsync(file) | |
.then(() => true) | |
.catch(() => false) | |
const mimeTypes = { | |
html: 'text/html', | |
jpeg: 'image/jpeg', | |
jpg: 'image/jpeg', | |
png: 'image/png', | |
svg: 'image/svg+xml', | |
js: 'text/javascript', | |
css: 'text/css', | |
map: 'application/octet-stream', | |
ttf: 'font/ttf', | |
otf: 'font/otf', | |
json: 'application/json' | |
} | |
const port = process.env.PORT || 1337 | |
const storage = process.env.STORAGE | |
const serveSPA = process.env.SERVE_SPA === 'true' | |
http.createServer(async (req, res) => { | |
const pathname = url.parse(req.url).pathname | |
const uri = pathname === '/' ? 'index.html' : pathname | |
let filename = join(storage, uri) | |
const exists = await fileExists(filename) | |
if (!exists) { | |
if (!serveSPA) { | |
console.log('not found:' + filename) | |
res.writeHead(404, { 'Content-Type': 'text/plain' }) | |
res.write('404 Not Found\n') | |
res.end() | |
return | |
} | |
else { | |
filename = join(storage, 'index.html') | |
} | |
} | |
const mimeType = mimeTypes[extname(filename).split('.')[1]] | |
res.writeHead(200, { | |
'Content-Type': mimeType | |
}) | |
const fileStream = fs.createReadStream(filename) | |
fileStream.pipe(res) | |
}).listen(port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment