I'm trying to use busboy to allow clients to upload files to my Express web server.
I have the following middleware function I'm running for Express.
module.exports = (req, res, next) => {
req.files = {};
let busboy;
try {
busboy = new Busboy({
headers: req.headers
});
} catch (e) {
return next();
}
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
req.files[fieldname] = {
file,
filename,
encoding,
mimetype
};
// Need to call `file.resume` to consume the stream somehow (https://stackoverflow.com/a/24588458/894067)
file.resume();
});
busboy.on("finish", next);
req.pipe(busboy);
};
As you can see, I had to add file.resume();
so that the "finish" event would be triggered, and call the next
function for the middleware (https://stackoverflow.com/a/24588458/894067).
The problem is, later on, when I want to consume the stream, it says readable: false
. So I'm assuming the file.resume();
discards the stream and doesn't allow it to be used in the future.
I basically want to get all the uploaded files and information associated with those files, store them on the req.files
object, then consume the streams later, or not consume them if I don't want to use it. That way they remain streams and don't take up much memory, until I'm ready to consume the stream and actually do something with it (or choose to discard it).
What can I use in place of file.resume();
to ensure that the "finish" event get triggers, while allowing me to use the stream later on in the lifecycle of the request (the actual app.post
routes, instead of middleware)?
The client might also upload multiple files. So I need any solution to handle multiple files.