Skip to content

Instantly share code, notes, and snippets.

@johnnymo87
Created November 26, 2013 04:42
Show Gist options
  • Save johnnymo87/7653580 to your computer and use it in GitHub Desktop.
Save johnnymo87/7653580 to your computer and use it in GitHub Desktop.
I just found out streams can deliver a lot of different kinds of content over the server without much hassle. More info: http://ejohn.org/blog/node-js-stream-playground/
var fs = require('fs');
util = require('util');
/**
* Exercise 1
* Make an HTTP server that serves files. The file path is provided in the URL like this: http://localhost:4000/path/to/my
*/
require('http').createServer(function(req, res) {
var file = '.' + req.url;
console.log(file);
fs.exists(file, function(exists) {
if (exists) {
fs.stat(file, function(err, stat) {
var rs;
if (err) { throw err; }
if (stat.isDirectory()) {
res.writeHead(403);
res.end('Forbidden');
} else {
rs = fs.createReadStream(file);
res.writeHead(200);
rs.pipe(res);
}
});
} else {
res.writeHead(404);
res.end('Not found');
}
})
}).listen(4000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment