T. Dimoff
T. Dimoff

Reputation: 565

Difference between generating a readable stream with fs and stream modules?

Making a readable stream with the fs module:

var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
    var stream = fs.createReadStream(__dirname + '/data.txt');
    stream.pipe(res);
});
server.listen(8000);

and instantiating it through the stream module:

var Readable = require('stream').Readable;

var rs = new Readable;
rs.push('file.txt');
rs.push('boop\n');
rs.push(null);

rs.pipe(process.stdout);

Upvotes: 5

Views: 6462

Answers (1)

Travis
Travis

Reputation: 699

The stream module allows you to create an in memory stream object that isn't actually tied to a file. It is meant to be used as a shared interface for providing stream like access. Typically a module will push data from some source to be consumed as a stream from consumers outside the module.

Creating a stream from the fs module, on the other hand, generates a stream object attached to a file, which means that the fs module uses the file as the source of the streamed data.

Upvotes: 2

Related Questions