访问节点ReadStream

时间:2017-07-28 07:25:06

标签: javascript node.js nodejs-stream

我有一段包含在承诺中的代码。这段代码从http中读取图像,执行各种操作,最后将其发送到aws.s3.putObject。它看起来像这样(简化): 请注意form是多方对象。

form.on('part', (part) => {//form is multiparty
    fileCount++;
    let tmpFile = path.join(os.tmpDir(), `${userId}_${timePrefix}_${path.basename(part.filename)}`);
    part.pipe(fs.createWriteStream(tmpFile));
    part.on('end', () => {
        resolve(fs.createReadStream(tmpFile));
    });
    part.once('error', (error) => {
        handleError(error);
    });
});

form.once('error', (error) => {
    handleError(error);
});

form.parse(request);
}).then((imageStream) => {
   //here is a call to AWS S3.putObject. Which return a promise
}).then(() => {
    return new Ok();
});

本质上,流在创建的映像上生成并发送到AWS。我想在二进制级别上进行一些操作(读取文件签名,以检查它是否是图像)。我让它像这样工作:

form.on('part', (part) => {
    fileCount++;

    let tmpFile = path.join(os.tmpDir(), `${userId}_${timePrefix}_${path.basename(part.filename)}`);
    part.pipe(fs.createWriteStream(tmpFile));
    part.on('end', () => {
        let chunk = [];
        let file = fs.createReadStream(tmpFile);
        let isFirstChunkSet = false;
        file.on('data', function(chunks) {
            if (!isFirstChunkSet){
                chunk = chunks;
                isFirstChunkSet = true;
            }
        });

        file.on('close', function() {
            let magicNumber = chunk.toString('hex', 0, 2);           

            if (imageProperties.allowed_file_types.includes(magicNumber)) {
                resolve(fs.createReadStream(tmpFile));
            } else {
                error.message = 'wrong file type';
                handleError(error);
            }
        });
    });
    part.once('error', (error) => {
        handleError(error);
    });
});

form.once('error', (error) => {
    handleError(error);
});

form.parse(request);
}).then((imageStream) => {
    //here is a call to AWS S3.putObject. Which return a promise
}).then(() => {
    return new Ok();
});

基本上我将两个事件监听器附加到现有流来访问数据,因此检查了头文件。

困扰我的是我在这里做事太过分的感觉。我想避免那两个监听器(数据和关闭)并尽可能读取流。

更准确地说,这部分代码接收流,在其中我希望在将数据发送到AWS之前访问它。此流已准备好,只需将如何阅读,而不使用事件?

form.parse(request);
}).then((imageStream) => {
    //How can I access the imageStream here, without event listeners.
    //Assumption is the stream is ready to be accessed.

    //here is a call to AWS S3.putObject. Which return a promise
}).then(() => {
    return new Ok();
});

0 个答案:

没有答案