D
D
Dron Krzh2014-09-22 23:39:42
JavaScript
Dron Krzh, 2014-09-22 23:39:42

How to make a Transform Stream?

Hey Ya!
There is a task, to file a class for loading a file (nodejs) must be able to write and read the file.
Theory:

var utils = require('utils');
var TransformStream = require('stream').TransformStream;

function WriteReadStream(path, options) {
  TransformStream.call(this);
}

WriteReadStream.prototype._transform = function(chunk, encoding, cb) {
  // что то нужно сделать здесь
};

utils.inherit(WriteReadStream, TransformStream);

We write a file:
var file = new WriteReadStream('/tmp/file');
req.pipe(file);

And then we can read:
var file = new WriteReadStream('/tmp/file');
file.pipe(res);

Is this even possible? Or does it need 2 handles for writing (fs.createWriteStream) and reading (fs.createReadStream)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Shemsedinov, 2014-09-23
@MarcusAurelius

Do not inherit from there, see the example in the source code of the node in /lib/crypto.js
For example, the Hash class is written like this, it inherits LazyTransform, like this: util.inherits(Hash, LazyTransform); then LazyTransform inherits from stream.Transform like this: util.inherits(LazyTransform, stream.Transform); and then the _transform method is defined

Hash.prototype._transform = function(chunk, encoding, callback) {
  this._binding.update(chunk, encoding);
  callback();
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question