直接将AWS S3文件下载到目录

时间:2018-08-13 15:19:26

标签: node.js amazon-web-services amazon-s3

我想将从AWS S3下载的文件自动保存到我的应用程序文件夹中。现在,这可以手动完成。下面的代码:

    router.get("/download", (req, res) => {
    //File S3 URL
    var fileKey =
        "key";

    AWS.config.update({
        accessKeyId: IAM_USER_KEY,
        secretAccessKey: IAM_USER_SECRET,
        Bucket: BUCKET_NAME
    });

    var s3 = new AWS.S3();
    var file = fs.createWriteStream("test.csv");

    var options = {
        Bucket: "name",
        Key: fileKey
    };

    res.attachment(fileKey);

    var fileStream = s3
        .getObject(options)
        .createReadStream()
        .on("error", error => {
        console.log(error);
        res.json({ error: "An error has occured, check console." });
        })
        .on("httpData", function(data) {

        file.write(data);
        })
        .on("httpDone", function() {
        file.end();
        });

    fileStream.pipe(res);
    //   fse.writeFileSync("text.csv");
    });

如前所述,可以手动下载和保存文件。但是如何写文件并将其自动保存到特定的文件夹中?

谢谢

2 个答案:

答案 0 :(得分:4)

下面是将S3对象下载到特定本地文件的示例:

const AWS = require('aws-sdk');
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {Bucket: 'mybucket', Key: 'test.csv'};
var file = require('fs').createWriteStream('/tmp/test.csv');
s3.getObject(params).createReadStream().pipe(file);

答案 1 :(得分:0)

jarmod 的回答代码,承诺:

const AWS = require('aws-sdk');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
const params = {Bucket: 'mybucket', Key: 'test.csv'};
const file = require('fs').createWriteStream('/tmp/test.csv');

new Promise((resolve, reject) => {
  const pipe = s3.getObject(params).createReadStream().pipe(file);
  pipe.on('error', reject);
  pipe.on('close', resolve);
});