Last active
December 15, 2016 16:02
-
-
Save friedemannsommer/fcf9003a7a952ba9b4316ccd35151040 to your computer and use it in GitHub Desktop.
dependency free node file server (only for debugging purpose)
This file contains 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 http = require('http') | |
const path = require('path') | |
const url = require('url') | |
const fs = require('fs') | |
const port = 8080 | |
const mimeTypes = { | |
'.html': 'text/html', | |
'.js': 'application/javascript', | |
'.css': 'text/css', | |
'.json': 'application/json', | |
'.png': 'image/png', | |
'.jpg': 'image/jpg', | |
'.jpeg': 'image/jpeg', | |
'.gif': 'image/gif', | |
'.wav': 'audio/wav', | |
'.mp4': 'video/mp4', | |
'.woff': 'application/font-woff', | |
'.ttf': 'application/font-ttf', | |
'.eot': 'application/vnd.ms-fontobject', | |
'.otf': 'application/font-otf', | |
'.svg': 'application/image/svg+xml', | |
'.txt': 'text/plain' | |
} | |
function sendError(err, res) { | |
res.setHeader('Content-Type', 'text/plain') | |
res.writeHead(500) | |
res.end(err + '') | |
} | |
function handleRequest(req, res) { | |
const pathName = url.parse(req.url).pathname.slice(1) | |
const filePath = path.resolve(__dirname, pathName) | |
const extName = path.extname(filePath).toLowerCase() | |
const contentType = mimeTypes[extName] || 'application/octect-stream' | |
fs.stat(filePath, (err, stats) => { | |
if (err) { | |
sendError(err, res) | |
} else { | |
if (stats.isFile()) { | |
fs.access(filePath, fs.constants.R_OK, (err) => { | |
if (err) { | |
sendError(err, res) | |
} else { | |
const stream = fs.createReadStream(filePath, { | |
flags: 'r', | |
encoding: 'utf8', | |
autoClose: true | |
}) | |
res.setHeader('Content-Type', contentType) | |
res.writeHead(200) | |
stream.on('data', (chunk) => { | |
if(!res.finished) { | |
res.write(chunk) | |
} | |
}) | |
stream.on('end', () => { | |
if(!res.finished) { | |
res.end() | |
} | |
}) | |
stream.on('error', (err) => { | |
if(!res.finished) { | |
res.end(err + '') | |
} | |
}) | |
} | |
}) | |
} else { | |
sendError(new Error('Directories are not supported! Try a specific file instead.'), res) | |
} | |
} | |
}) | |
} | |
const server = new http.Server() | |
server.on('listening', () => { | |
const address = server.address() | |
console.info(`server running @ ${address.address}:${address.port}`) | |
}) | |
server.on('request', handleRequest) | |
server.listen(port) | |
process.on('exit', () => { | |
server.close() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment