尝试 return 来自函数的流缓冲区

Trying to return a stream-buffer from a function

我正在尝试创建一个包含 csv 文件的 zip 文件,并且 return 它来自一个函数作为缓冲区。我的代码如下:

const archiver = require('archiver');
const streamBuffers = require("stream-buffers");

createZipFromCsv(csv) {

  var myWritableStreamBuffer = new streamBuffers.WritableStreamBuffer({
    initialSize: (100 * 1024),   // start at 100 kilobytes.
    incrementAmount: (10 * 1024) // grow by 10 kilobytes each time buffer overflows.
  });

  myWritableStreamBuffer.on('finish', () => {
    console.log(myWritableStreamBuffer.getContents())
    return Promise.resolve(myWritableStreamBuffer.getContents());
  });

  const archive = archiver('zip');
  archive.pipe(myWritableStreamBuffer);
  archive.append(csv, { name: 'csvName.csv' });
  archive.finalize();

}

函数调用:

const buffer = await createZipFromCsv("some,csv,data");
console.log(buffer)

但是,函数调用后的缓冲控制台日志未定义。 console log里面的on finish returns是一个很好的缓冲区,但是只有在函数调用之后的console log之后。我很困惑为什么函数在缓冲区完成写入之前 returning。

感谢任何帮助!

您需要将您的代码包装在您 return 然后 resolve/reject 的承诺中。这是一种方法:

const archiver = require('archiver');
const streamBuffers = require("stream-buffers");

createZipFromCsv(csv) {

    return new Promise((resolve, reject) => {
        const myWritableStreamBuffer = new streamBuffers.WritableStreamBuffer({
            initialSize: (100 * 1024), // start at 100 kilobytes.
            incrementAmount: (10 * 1024) // grow by 10 kilobytes each time buffer overflows.
        });

        myWritableStreamBuffer.on('finish', () => {
            resolve(myWritableStreamBuffer.getContents());
        });

        myWritableStreamBuffer.on('error', reject);

        const archive = archiver('zip');
        archive.pipe(myWritableStreamBuffer);
        archive.append(csv, { name: 'csvName.csv' });
        archive.finalize();

    });
}