Last active
November 2, 2017 09:59
-
-
Save daliborgogic/79dea5c89ef25bf2ac44106cf7e5fc10 to your computer and use it in GitHub Desktop.
micro static file server
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
// Native | |
const http2 = require('http2') | |
const url = require('url') | |
const fs = require('fs') | |
const path = require('path') | |
// Packages | |
const { run, send } = require('micro') | |
const cert = require('openssl-self-signed-certificate') | |
const mime = require('mime') | |
const PORT = process.env.PORT || 3443 | |
const options = { | |
key: cert.key, | |
cert: cert.cert, | |
passphrase: cert.passphrase | |
} | |
const microHttp2 = fn => http2.createSecureServer(options, (req, res) => run(req, res, fn)) | |
const server = microHttp2(async (req, res) => { | |
const parseUrl = url.parse(req.url) | |
let file = `.${parseUrl.pathname}` | |
fs.exists(file, exist => { | |
if (!exist) { | |
send(res, 404) | |
return | |
} | |
if (fs.statSync(file).isDirectory()) { | |
file += '/index.html' | |
} | |
fs.readFile(file, (err, data) => { | |
if (err) { | |
send(res, 500) | |
} else { | |
res.setHeader('Content-type', mime.getType(file)) | |
send(res, 200, data) | |
} | |
}) | |
}) | |
}) | |
server.listen(PORT) |
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
const url = require('url') | |
const fs = require('fs') | |
const path = require('path') | |
const { send } = require('micro') | |
const mime = require('mime') | |
module.exports = async (req, res) => { | |
const parsedUrl = await url.parse(req.url) | |
let pathName = `.${parsedUrl.pathname}` | |
fs.exists(pathName, exist => { | |
if (!exist) { | |
send(res, 404) | |
return | |
} | |
if (fs.statSync(pathName).isDirectory()) { | |
pathName += '/index.html' | |
} | |
fs.readFile(pathName, (err, data) => { | |
if(err){ | |
send(res, 500) | |
} else { | |
res.setHeader('Content-type', mime.getType(pathName)) | |
send(res, 200, data) | |
} | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment