How do you handle errors gracefully with streams? My code is becoming really ugly and adding .on('error', () => …) after every .pipe(…) is pain in neck. Is there another way? I read about NodeJS domain but it’s deprecated.
How do you handle errors if they occur somewhere in the middle of the stream? In my case, by that time some of the transformed content has already been transferred back to the user.
<form>.To put it shortly: You add a file, submit the form, and you get a transformed file back.
The following code uses express for handling HTTP requests and busboy for handling file upload:
export default Router()
.get('/', renderPage)
.post('/', (req, res, next) => {
const busboy = new Busboy({ headers: req.headers })
const parser = myParser()
const transformer = myTransformer()
busboy.on('file', (_fieldname, file, filename) => {
res.setHeader('Content-disposition', `attachment; filename=${filename}`)
file
.pipe(parser)
.on('error', err => errorHandler(err, req, res))
.pipe(transformer)
.on('error', err => errorHandler(err, req, res))
.pipe(res)
.on('error', err => errorHandler(err, req, res))
})
.on('error', err => errorHandler(err, req, res))
req.pipe(busboy)
.on('error', err => errorHandler(err, req, res))
})
You should check out pump. Seems like it might help with your issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With