使用Javascript从S3下载

时间:2017-10-19 23:08:08

标签: javascript node.js amazon-s3

我有一个javascript文件,我试图用来从我的一个S3存储桶下载文本文件。但是当我使用“node file.js”执行此文件时,没有任何反应/返回。这里有什么问题我应该打电话吗?谢谢!

var AWS = require('aws-sdk');
var s3 = new AWS.S3();

var credentials = new AWS.SharedIniFileCredentials({profile: 'personal-account'});
AWS.config.credentials = credentials;

s3.getObject(
  { Bucket: "mybucket", Key: "testing.txt" },
  function (error, data) {
    if (error != null) {
      alert("Failed to retrieve an object: " + error);
    } else {
      alert("Loaded " + data.ContentLength + " bytes");
    }
  }
);

print("this file has been executed")

2 个答案:

答案 0 :(得分:2)

javascript中没有print函数,nodejs环境中没有alert

所以你必须使用类似console.log的东西。

var AWS = require('aws-sdk');
var s3 = new AWS.S3();

var credentials = new AWS.SharedIniFileCredentials({profile: 'personal-account'});
AWS.config.credentials = credentials;

s3.getObject(
  { Bucket: "mybucket", Key: "testing.txt" },
  function (error, data) {
    if (error != null) {
      console.log("Failed to retrieve an object: " + error);
    } else {
      console.log("Loaded " + data.ContentLength + " bytes");
    }
  }
);

console.log("this file has been executed")

但如果您没有看到任何输出,甚至是错误,那么您的设置就会出现问题。而且很难说清楚到底是什么。

答案 1 :(得分:0)

设置凭据后创建S3客户端:

var AWS = require('aws-sdk');

var credentials = new AWS.SharedIniFileCredentials({profile: 'personal-account'});
AWS.config.credentials = credentials;

var s3 = new AWS.S3();

s3.getObject(
  { Bucket: "mybucket", Key: "testing.txt" },
  function (error, data) {
    if (error != null) {
      console.log("Failed to retrieve an object: " + error);
    } else {
      console.log("Loaded " + data.ContentLength + " bytes");
    }
  }
);

console.log("this file has been executed");