Skip to content

Instantly share code, notes, and snippets.

@jonlabelle
Created March 21, 2014 16:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jonlabelle/9689998 to your computer and use it in GitHub Desktop.
Save jonlabelle/9689998 to your computer and use it in GitHub Desktop.
Simple node.js static file server.
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