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
?
asPromise
can be problematic depending on how you implement it. If you create the promise beforeasPromise
is called, and if you reject that Promise due to an error occuring in th stream, then you can get a unhandled promise rejection warning if your code does not use.asPromise
at all, and that waring will result in a real error in future that will exit the application. \$\endgroup\$asPromise
implies that this Promise is created on demand whenasPromise
is called. And not that it already exist before that call. So writing onlyr.pipe(encrypt).pipe(c);
should at least not result in a unhandled promise rejection warning. Just because it would break the expectation. \$\endgroup\$)
at.then()
. Why is second parameter to.then()
or.catch()
not used to handle error? Does the code at the question return the expected result? \$\endgroup\$