Created
March 21, 2014 16:25
-
-
Save jonlabelle/9689998 to your computer and use it in GitHub Desktop.
Simple node.js static file server.
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
var path = require('path'); | |
var fs = require('fs'); | |
// | |
// Configuration | |
// | |
var config = { | |
// www root | |
root: 'dist', | |
// default file to serve | |
index: 'index.html', | |
// http listen port | |
port: process.env.PORT || 3000 | |
}; | |
// | |
// HTTP Server | |
// | |
require('http').createServer(function (request, response) { | |
var file = path.normalize(config.root + request.url); | |
file = (file == config.root + '/') ? file + config.index : file; | |
console.log('Trying to serve: ', file); | |
function showError(error) { | |
console.log(error); | |
response.writeHead(500); | |
response.end('Internal Server Error'); | |
} | |
fs.exists(file, function (exists) { | |
if (exists) { | |
fs.stat(file, function (error, stat) { | |
var readStream; | |
if (error) { | |
return showError(error); | |
} | |
if (stat.isDirectory()) { | |
response.writeHead(403); | |
response.end('Forbidden'); | |
} | |
else { | |
readStream = fs.createReadStream(file); | |
readStream.on('error', showError); | |
response.writeHead(200); | |
readStream.pipe(response); | |
} | |
}); | |
} | |
else { | |
response.writeHead(404); | |
response.end('Not found'); | |
} | |
}); | |
}).listen(config.port, function() { | |
console.log('Server running at http://localhost:%d', config.port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment