简体   繁体   English

如何将Node.js二进制流从zip写入S3

[英]How to write Node.js binary stream from zip to an S3

I want to zip up files and dump the binary output right to AWS S3. 我想压缩文件并将二进制输出转储到AWS S3。 I'm testing out my code first by making sure it can even write to a local ZIP file, which is not working. 我正在测试我的代码,确保它甚至可以写入本地ZIP文件,这是无效的。

function zipFiles(filenames) {
  return new Promise((resolve, reject) => {
    const child = spawn(zipCmd, ['-'].concat(filenames));
    let buffer = '';

    child.stdout.on('data', (data) => {
      buffer += data.toString();
    });

    child.stderr.on('data', (data) => {
      // console.error(data.toString());
    });

    child.on('close', (code) => {
      fs.writeFileSync('testing.zip', buffer);
      resolve(code);
    });
  });
}

This results in a mangled zip file. 这会导致损坏的zip文件。 I'm not really sure how to handle the buffer stream from spawn and assemble it into something that will work with s3.putObject and fs.writeFileSync (as a method of testing). 我不确定如何处理来自spawn的缓冲流并将其组装成可与s3.putObjectfs.writeFileSync一起使用的东西(作为测试方法)。

Got it! 得到它了!

function zipFiles(filenames) {
  return new Promise((resolve, reject) => {
    const out = fs.openSync('testing.zip', 'a');
    const child = spawn(zipCmd, ['-'].concat(filenames));
    let buffer = new Buffer('');

    child.stdout.on('data', (data) => {
      buffer = Buffer.concat([buffer, data]);
    });

    child.stderr.on('data', (data) => {
      // console.error(data.toString());
    });

    child.on('close', (code) => {
      fs.writeFileSync('testing.zip', buffer);
      resolve(code);
    });
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM