Skip to content

Commit

Permalink
added
Browse files Browse the repository at this point in the history
  • Loading branch information
Paolo Fragomeni committed Jan 23, 2012
0 parents commit 8b467ee
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
27 changes: 27 additions & 0 deletions 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);
```

<a class="button download" href="#">Download Code Sample</a>
7 changes: 7 additions & 0 deletions 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
}
22 changes: 22 additions & 0 deletions 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);

0 comments on commit 8b467ee

Please sign in to comment.