Node.js ArchiverJS 库未写入 AWS Lambda 中的输出文件流

Node.js ArchiverJS library not writing to output filestream in AWS Lambda

我正在尝试使用 node-archiver as suggested here 压缩目录的内容。该函数在 Node.js 运行时环境中的 AWS Lambda 中 运行。

我的函数如下:

function zipDirectory(source, outputTarget) {
    var archive = archiver("zip");
    const stream = fs.createWriteStream(outputTarget, { flags: 'w' });

    stream.on("close", () => {
        console.log(archive.pointer() + ' total bytes');
        console.log('archiver has been finalized and the output file descriptor has closed.');
    });

    return new Promise((resolve, reject) => {
        archive.pipe(stream);
        archive.on("error", err => reject(err))
        archive.directory(source, false);
        archive.finalize();
        stream.close();
        resolve();
    });
}

结果是创建了 zip 但文件大小为零:

INFO    0 total bytes
INFO    archiver has been finalized and the output file descriptor has closed.

我也无法提取存档,出现以下错误。

INFO    Error: end of central directory record signature not found

备注:

  1. 源目录肯定存在,已填充,路径正确。
  2. 所有内容都被写入 /tmp/ 目录,AWS Lambda 允许我们对其进行读写访问。
  3. 我尝试使用 Lambda 部署包上传 zip 二进制文件并将其作为子进程 运行 上传,但显然不支持,因为它是 32 位包。如果您有我可以用来在 Lambda 运行时工作的节点外压缩目录的替代方法,请告诉我。

感谢任何帮助,谢谢!

好吧,搞清楚我的错误了。

  1. archive.finalize() returns 一个承诺,函数在归档完成之前返回。
  2. 不需要调用 stream.close(),因为 archive.finalize() 已经为您完成了,所以无论归档是否完成,流都会被关闭。

正确的代码如下所示:

function zipDirectory(source, outputTarget) {
    var archive = archiver("zip");
    const stream = fs.createWriteStream(outputTarget, { flags: 'w' });

    stream.on("close", () => {
        console.log(archive.pointer() + ' total bytes');
        console.log('archiver has been finalized and the output file descriptor has closed.');
    });

    return new Promise(async (resolve, reject) => {
        archive.pipe(stream);
        archive.on("error", err => reject(err))
        archive.directory(source, false);
        await archive.finalize();
        resolve();
    });
}