Created
August 18, 2017 06:25
-
-
Save khaled0fares/7471c5fb51817df95a956943d72d2027 to your computer and use it in GitHub Desktop.
simple static handler in nodejs
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 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