Problem
I need to collect all the data from the stream and resolve it as promise.
I created this stream:
class CollectToPromise extends Writable {
constructor(options) {
super();
this._result = ""
this.result = new Promise((resolve, reject) => {
this.on('finish', resolve):w
this.on('error', reject)
}).then(() => this._result)
}
_write(chunk, encoding, callback) {
this._result += chunk
callback()
}
_writev(chunks, callback) {
chunks.forEach(c => {
this._result += chunk
})
callback()
}
asPromise() {
return this.result
}
}
and I use it like this:
var r = fs.createReadStream('secrets');
const c = new CollectToPromise()
const encrypt = crypto.createCipher(algorithm, password);
r.pipe(encrypt).pipe(c).asPromise().then((res) => console.log(res)
My questions are:
- What do you think about the solution, including the naming?
- How can I avoid the warning:
(node:32386) Warning: Use Cipheriv for counter mode of aes-256-ctr
?
Solution
I am not sure I understand why you are attempting to extend Writable
here.
At the end of the day, it seems as if your pipeline is what you are REALLY wanting to have a promise interface.
Luckily this is really easy to do with recent versions of node using Stream.pipeline
and Util.promisify()
. There is an even an example in the Stream.pipeline documentation