diff --git a/article.html b/article.html new file mode 100644 index 0000000..f9ea896 --- /dev/null +++ b/article.html @@ -0,0 +1,27 @@ +The function `fs.createReadStream()` allows you to open up a readable stream in a very simple manner. All you have to do is pass the path of the file to start streaming in. It turns out that the response (as well as the request) objects are streams. So we will use this fact to create a http server that streams the files to the client. Since the code is simple enough, it is pretty easy just to read through it and comment why each line is necessary. + +```js +var http = require('http'); +var fs = require('fs'); + +http.createServer(function(req, res) { + // The filename is simple the local directory and tacks on the requested url + var filename = __dirname+req.url; + + // This line opens the file as a readable stream + var readStream = fs.createReadStream(filename); + + // This will wait until we know the readable stream is actually valid before piping + readStream.on('open', function () { + // This just pipes the read stream to the response object (which goes to the client) + readStream.pipe(res); + }); + + // This catches any errors that happen while creating the readable stream (usually invalid names) + readStream.on('error', function(err) { + res.end(err); + }); +}).listen(8080); +``` + +Download Code Sample \ No newline at end of file diff --git a/article.json b/article.json new file mode 100644 index 0000000..84e92ab --- /dev/null +++ b/article.json @@ -0,0 +1,7 @@ +{ + "title":"How to use fs.createReadStream?", + "date": "Fri Aug 26 2011 03:08:50 GMT-0700 (PST)", + "tags": ["core", "streams", "fs"], + "author": "Nico Reed", + "difficulty": 3 +} diff --git a/readable-stream.js b/readable-stream.js new file mode 100644 index 0000000..b72b7d2 --- /dev/null +++ b/readable-stream.js @@ -0,0 +1,22 @@ +var http = require('http'); +var fs = require('fs'); + +http.createServer(function(req, res) { + // The filename is simple the local directory and tacks on the requested url + var filename = __dirname+req.url; + + // This line opens the file as a readable stream + var readStream = fs.createReadStream(filename); + + // This will wait until we know the readable stream is actually valid before piping + readStream.on('open', function () { + // This just pipes the read stream to the response object (which goes to the client) + readStream.pipe(res); + }); + + // This catches any errors that happen while creating the readable stream (usually invalid names) + readStream.on('error', function(err) { + res.end(err); + }); +}).listen(8080); +