Created
June 22, 2018 22:04
-
-
Save daliborgogic/1ef7ce4f43799a22f73468a0d7a71549 to your computer and use it in GitHub Desktop.
Micro serve
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 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) | |
} | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment