Sometimes, we want to download a file to disk from an AWS S3 bucket with Node.js.
In this article, we’ll look at how to download a file to disk from an AWS S3 bucket with Node.js.
How to download a file to disk from an AWS S3 bucket with Node.js?
To download a file to disk from an AWS S3 bucket with Node.js, we can create a read steam from the S3 client.
For instance, we write
const AWS = require("aws-sdk");
const path = require("path");
const fs = require("fs");
AWS.config.loadFromPath(path.resolve(__dirname, "config.json"));
AWS.config.update({
accessKeyId: AWS.config.credentials.accessKeyId,
secretAccessKey: AWS.config.credentials.secretAccessKey,
region: AWS.config.region,
});
const s3 = new AWS.S3();
const params = {
Bucket: "<your-bucket>",
Key: "<path-to-your-file>",
};
const readStream = s3.getObject(params).createReadStream();
const writeStream = fs.createWriteStream(path.join(__dirname, "s3data.txt"));
readStream.pipe(writeStream);
to call s3.getObject
to get the object from the bucket.
Then we call createReadStream
from the returned object to read the file.
Next, we call fs.createWriteStream
with the path to write to.
And then we call readStream.pipe
with the writeStream
to pipe the read stream data into the write stream to write the file to disk.
Conclusion
To download a file to disk from an AWS S3 bucket with Node.js, we can create a read steam from the S3 client.