Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Created June 22, 2018 22:04
Show Gist options
  • Save daliborgogic/1ef7ce4f43799a22f73468a0d7a71549 to your computer and use it in GitHub Desktop.
Save daliborgogic/1ef7ce4f43799a22f73468a0d7a71549 to your computer and use it in GitHub Desktop.
Micro serve
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