从流返回值到父函数

Returning value from stream to parent function

我有一个用于将一些文本写入云存储桶的流。 完成后,我希望将一条消息返回给父函数。

我尝试返回缓冲流,但这给了我整个缓冲流对象。我只想回消息。

例如如果我有另一个调用 toBucket 的函数,我希望返回文件已上传的消息,以便我可以在浏览器中显示它。

我该如何解决这个问题?

const toBucket = (message, filename) => {
  const storage = new Storage();
  // Initiate the source
  const bufferStream = new stream.PassThrough();
  // Write your buffer
  bufferStream.end(Buffer.from(message));

  const myBucket = storage.bucket(process.env.BUCKET);
  const file = myBucket.file(filename);
  // Pipe the 'bufferStream' into a 'file.createWriteStream' method.
  bufferStream
    .pipe(
      file.createWriteStream({
        validation: 'md5',
      })
    )
    .on('error', (err) => {
      // eslint-disable-next-line no-console
      console.error(err);
    })
    .on('finish', () => {
      // The file upload is complete.
      const message = `${filename} is uploaded!`;
      // eslint-disable-next-line no-console
      console.log(message);
      return message;
    });
};

用于

() => async {
await things happening...

const saved = toBucket(message,filename);

sendToBrowser(saved);

}

toBucket 函数应该 return 一个 promise,然后你可以 await 它在你的父函数中。为此,只需将 toBucket 的逻辑包装到一个 promise

const toBucket = (message, filename) => {
    return new Promise((resolve, reject) => { // return a promise
        const storage = new Storage();
        // Initiate the source
        const bufferStream = new stream.PassThrough();
        // Write your buffer
        bufferStream.end(Buffer.from(message));

        const myBucket = storage.bucket(process.env.BUCKET);
        const file = myBucket.file(filename);
        // Pipe the 'bufferStream' into a 'file.createWriteStream' method.
        bufferStream
            .pipe(
                file.createWriteStream({
                    validation: 'md5',
                })
            )
            .on('error', (err) => {
                // eslint-disable-next-line no-console
                console.error(err);
                reject(err); // reject when something went wrong
            })
            .on('finish', () => {
                // The file upload is complete.
                const message = `${filename} is uploaded!`;
                // eslint-disable-next-line no-console
                console.log(message);
                // return message;
                resolve(message); // return message and finish
            });
    })
};

在父函数中:

() => async {
    await things happening...
    
    const saved = await toBucket(message,filename); // await
    
    sendToBrowser(saved);
}