简体   繁体   English

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

[英]Download AWS S3 file directly to a directory

I want to automatically save the file im downloading from AWS S3 to my application folder.我想自动保存从 AWS S3 下载的文件到我的应用程序文件夹。 Right now this can be done manually.现在这可以手动完成。 Code below:代码如下:

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

As mentioned before, the file can be download and saved manually.如前所述,该文件可以手动下载和保存。 But how can write the file and save it automatically in an specific folder?但是如何编写文件并将其自动保存在特定文件夹中?

Thank you谢谢

Here's an example of downloading an S3 object to a specific local file:以下是将 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);

The code for jarmod's answer, promisified: jarmod 的答案的代码,promisified:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM