Skip to content

Instantly share code, notes, and snippets.

@friedemannsommer
Last active December 15, 2016 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save friedemannsommer/fcf9003a7a952ba9b4316ccd35151040 to your computer and use it in GitHub Desktop.
Save friedemannsommer/fcf9003a7a952ba9b4316ccd35151040 to your computer and use it in GitHub Desktop.
dependency free node file server (only for debugging purpose)
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