Skip to content

Instantly share code, notes, and snippets.

@khaled0fares
Created August 18, 2017 06:25
Show Gist options
  • Save khaled0fares/7471c5fb51817df95a956943d72d2027 to your computer and use it in GitHub Desktop.
Save khaled0fares/7471c5fb51817df95a956943d72d2027 to your computer and use it in GitHub Desktop.
simple static handler in nodejs
const http = require('http')
const fs = require('fs')
const mime = require('mime')
const server = http.createServer().listen(3000)
server.on('request', (req, res)=>{
const filePath = __dirname + req.url
fs.stat(filePath, (err, stat)=>{
if(err || !stat.isFile()){
res.writeHead(404)
res.write('File Not Found')
res.end()
return
}
res.setHeader('Content-Type', mime.lookup(filePath))
const file = fs.createReadStream(filePath)
file.on('open', ()=>{
res.statusCode = 200
file.pipe(res)
})
file.on('error', ()=>{
res.statusCode = 403
res.write('Permission Denied.')
res.end()
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment