1

I want to pass original file stream pass down to other layer of code which will handle later drop on disk (upload to cloud storage) behavior. As files size might be large I can't actually fully buffer incoming file. I assume that PassThrough stream should pass needed data. While file.resume already called, finish event never get called.

How can I collect all required form fields along with single file stream and make proper service call, without explicit whole file in memory storage or on local disk, as I have a few of both of them?

private collectMultipartRequest (req: Request, fileFieldName: string): Promise<{ file: IFile, fields: { [k: string]: string }}> {
        const obj = {
            file: null,
            fields: {}
        };

        return new Promise ((resolve, reject) => {
            const busboy = new Busboy({ headers: req.headers, limits: { files: 1 }});

            busboy.on("file", (fieldname, file, filename, mimetype) => {
                if (fieldname === fileFieldName) {
                    const passThrough = new PassThrough();
                    file.pipe(passThrough);

                    obj.file = <IFile>{
                        mimeType: mimetype,
                        name: filename,
                        readStream: passThrough
                    };
                }
                file.resume();
            });

            busboy.on("field", (fieldName, val) => {
                obj.fields[fieldName] = val;
            });

            busboy.on("filesLimit", () => {
                reject(obj);
            });

            busboy.on("finish", async () => {
                resolve(obj);
            });

            req.pipe(busboy);
        });
    }
Artsiom Miksiuk
  • 3,896
  • 9
  • 33
  • 49
  • I'm almost sure it's not possible. What you actually want to do is defer parts of stream for later reading, which is not possible because stream data is transferred in order. – Avraham Sep 26 '19 at 21:10

0 Answers0