Sometimes, we want to add error handling to Node.js streams.
In this article, we’ll look at how to add error handling to Node.js streams.
How to add error handling to Node.js streams?
To add error handling to Node.js streams, we call pipeline
with all the operators before the error handler.
For instance, we write
const {
pipeline,
finished
} = require('stream');
pipeline(
input,
transformA,
transformB,
transformC,
(err) => {
if (err) {
console.error('Pipeline failed', err);
} else {
console.log('Pipeline succeeded');
}
});
finished(input, (err) => {
if (err) {
console.error('Stream failed', err);
} else {
console.log('Stream is done reading');
}
});
to call pipeline
with the operators input
, transformA
, and transformB
, and transformC
.
Then we pass in the error handler callback so that errors with any of the operators will be picked up by it.
Then we call finished
with input
to handle any errors with input
.
Conclusion
To add error handling to Node.js streams, we call pipeline
with all the operators before the error handler.