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

时间:2016-10-16 07:55:01

标签: javascript node.js amazon-s3 buffer

我想压缩文件并将二进制输出转储到AWS S3。我首先测试我的代码,确保它甚至可以写入本地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);
    });
  });
}

这会导致损坏的zip文件。我不确定如何处理来自spawn的缓冲流并将其组合成可与s3.putObjectfs.writeFileSync一起使用的东西(作为测试方法)。

1 个答案:

答案 0 :(得分:0)

知道了!

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);
    });
  });
}