Skip to content

Instantly share code, notes, and snippets.

@jmnarloch
Last active December 10, 2015 10:28
Show Gist options
  • Save jmnarloch/4420853 to your computer and use it in GitHub Desktop.
Save jmnarloch/4420853 to your computer and use it in GitHub Desktop.
Node based simple Http Server for serviing static files.
#!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var optimist = require('optimist');
var argv = optimist.usage('$0 --dir [base_directory] --port [port]')
.default({ dir: '.', port: 8080 })
.argv;
if (argv.help) {
optimist.showHelp(console.log);
return;
}
// creates the options from the command line arguments
var options = {
port: Number(argv.port),
dir: argv.dir,
};
require('http').createServer(function (req, res) {
// defines error handler
function handleError(err) {
console.log(err);
res.writeHead(500);
res.end('Internal Server Error');
}
console.log('Received request for file', req.url);
var file = path.normalize(options.dir + req.url);
// checks if file exists
path.exists(file, function (exists) {
if (exists) {
// checks if file is directory
fs.stat(file, function (err, stat) {
var fileStream;
if (err) {
handleError(err);
}
if (stat.isDirectory()) {
// does not allow directory listening
console.log('File is a directory', file);
res.writeHead(403);
res.end('Forbidden');
} else {
console.log('Coping the file', file);
fileStream = fs.createReadStream(file);
fileStream.on('error', handleError);
// writes the file to the output
fileStream.pipe(res);
}
});
} else {
// the file does not exists
console.log('File does not exists', file);
res.writeHead(404);
res.end('Not found');
}
});
}).listen(options.port);
console.log('Server up and running on port', options.port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment