Created
November 26, 2013 04:42
-
-
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/
This file contains hidden or 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 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