How to pipe a stream to s3.upload() with Node.js?

Sometimes, we want to pipe a stream to s3.upload() with Node.js.

In this article, we’ll look at how to pipe a stream to s3.upload() with Node.js.

How to pipe a stream to s3.upload() with Node.js?

To pipe a stream to s3.upload() with Node.js, we can use the s3.upload method with the stream.PassThrough method.

For instance, we write

const uploadFromStream = (s3) => {
  const pass = new stream.PassThrough();

  const params = {
    Bucket: BUCKET,
    Key: KEY,
    Body: pass
  };
  s3.upload(params, (err, data) => {
    console.log(err, data);
  });

  return pass;
}

inputStream
  .pipe(uploadFromStream(s3));

to create the uploadFromStream function that calls the stream.PassThrough method to return an object that we can use as the value of the Body property.

And then we call s3.upload with params that has the Bucket, Key, and Body.

Finally, we call inputStream.pipe with uploadFromStream(s3) to pipe the stream to the s3.upload method.

Conclusion

To pipe a stream to s3.upload() with Node.js, we can use the s3.upload method with the stream.PassThrough method.