Jimmy
Jimmy

Reputation: 3880

Download from S3 with Javascript

I have a single javascript file that I am trying to use to download a text file from one of my S3 buckets. However when I execute this file using "node file.js" nothing happens / gets returned. Is there something wrong here that I should be calling? Thanks!

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

Upvotes: 0

Views: 1194

Answers (2)

John Hanley
John Hanley

Reputation: 81464

Create the S3 Client after setting up your credentials:

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

Upvotes: 0

Jake
Jake

Reputation: 1439

There is no print function in javascript as well as no alert in nodejs environment.

So you have to use something like console.log instead.

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

But if you don't see any output, even errors, then something is completely wrong with your setup. And it is hard to tell what exactly.

Upvotes: 2

Related Questions