1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Node.jsでS3オブジェクトをまとめてZip圧縮してS3に保存する

Posted at

要点

Node.js Streamを使うことで、メモリやストレージにデータを保持せず、高速かつ省メモリに実現できる。

実装

AWS Lambda (Runtime: Node.js 16.x) を想定した実装になっている。事前に archiver をインストールしておくこと。

index.js
const archiver = require('archiver');
const { PassThrough } = require('stream');
const { S3 } = require('aws-sdk');

const s3 = new S3();

const bucket = 'bucket';
const keys = ['key1', 'key2', 'key3'];

exports.handler = async (event) => {

  const archive = archiver('zip');
  const output = new PassThrough();

  archive.pipe(output);

  keys.forEach((key) => archive.append(s3.getObject({ Bucket: bucket, Key: key }).createReadStream(), { name: key }));

  archive.finalize();

  await s3.upload({ Bucket: bucket, Key: 'archive.zip', Body: output }).promise();
};
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?