Retrieve files from Amazon S3 using JavaScript

I'm currently working with a javascript file that's intended to download a text file from one of my S3 buckets. However, after running this file using "node file.js", nothing happens and there's no output. Is there something I'm missing or doing wrong here? Appreciate any help!

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

Answer №1

JavaScript does not have a print function, and the nodejs environment does not support alert.

Instead, you should use something like 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")

If you are not seeing any output or errors, then there may be a problem with your setup that is difficult to diagnose.

Answer №2

Establish the S3 Client only after configuring 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 fetch object: " + error);
    } else {
      console.log("Retrieved " + data.ContentLength + " bytes");
    }
  }
);

console.log("execution of this file has been completed");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Splitting an array into multiple arrays with distinct names: A step-by-step guide

I have a data set that looks like this: [A,1,0,1,0,1,B,1,0,0,1,A,1]. I want to divide this array into smaller arrays. Each division will occur at the positions where "A" or "B" is found in the original array. The new arrays should be named with the prefix ...

executing jQuery toggle on freshly generated content

I have a webpage that I designed using jQuery. Within this page, there is a table with rows assigned specific color classnames (e.g., tr class="yellowclass"). Users can filter the rows by clicking checkboxes to show/hide tables of different colors. The i ...

The element is not defined in the Document Object Model

There are two global properties defined as: htmlContentElement htmlContentContainer These are set in the ngAfterViewInit() method: ngAfterViewInit() { this.htmlContentElement = document.getElementById("messageContent"); this.htmlContentCont ...

Issue with the Ajax auto-complete feature in Internet Explorer

I am facing an issue with my "ajax suggestion list" getting hidden behind the "select menu" located right below the text box that triggers the ajax function. This problem only occurs in IE 6.0, while it works fine in other browsers. I have already disabled ...

Looking for a fully customizable event and booking calendar?

Currently, I am searching for a unique event and booking calendar that provides the ability to customize each cell or day with our desired content. While most calendars only allow for inputting events as text, we require a solution that enables us to add ...

An undefined value is encountered in a function within Node.js

To test this code snippet in node.js v6.0.0: x = 3; var foo = { x:1, bar: { x: 2, baz: function() { console.log(this.x); } } }; foo.bar.baz(); var a = foo.bar.baz; a(); An error is thrown: 2 TypeError: Cannot read property &apos ...

Tips on parsing a CSV file from a Node/Express Axios GET request?

I am currently working on a Node/Express backend that utilizes axios to send a GET request to the following URL: https://marknadssok.fi.se/Publiceringsklient/sv-SE/Search/Search?SearchFunctionType=Insyn&Utgivare=&PersonILedandeSt%C3%A4llningNamn=&a ...

Having trouble getting the finally clause to work properly in Angular JS version 1.7

In my current project, I am utilizing Angular JS 1.7. Recently, I encountered an issue while using the finally clause within a promise: $http.put( url, null, { headers: { 'Content-Type': 'application/json' } } ).then( ...

The error message thrown by DynamoDB BatchGet is always 'The key element supplied does not align with the schema'

I've been struggling with the DynamoDB batchGet operation for quite some time now. Here's my table definition using serverless: Resources: MyTable: Type: AWS::DynamoDB::Table DeletionPolicy: Retain Properties: TableName: MyTab ...

Problem encountered while performing npm installation on Ubuntu due to ENOENT error with lstat

I've been working on a project that handles blog posts and recently deployed it on a cloud platform without any issues. However, I decided to clean up my node_modules folder by deleting it and reinstalling using npm install. After doing so, I encount ...

What is the best way to implement a delay before calling the owlCarousel function?

Is there a way to delay calling the owlCarousel function for 5 seconds? I attempted the following: $(document).ready(function(){ setInterval(function(){ $(".demo-slide").owlCarousel(); },5000); }); However, I encountered ...

Error: react/js encountered an unexpected token

While attempting to execute my project, I encountered an error in the console related to a function within the code. The exact error message reads as follows: "63:25 error Parsing error: Unexpected token, expected (function toggleDrawer = (open) => () => ...

Upon reloading the page, the Vue getter may sometimes retrieve an undefined value

My blog contains various posts. Clicking on a preview will direct you to the post page. Within the post page, I utilize a getter function to display the correct post (using the find method to return object.name which matches the object in the array). cons ...

The most recent release of Chrome (Version 47.0.2526.80 m) introduces an intriguing feature. When using navigator.webkitGetUserMedia, the returned stream now lacks a

I recently encountered a problem with my code that used to access the camera on Chrome browser and release it after use. Here's the code snippet: Starting the Camera: navigator.webkitGetUserMedia($scope.options.videoObj, function (stream) { $sco ...

Issue with JQuery on Mobile Devices: Troubles with Dropdown Menu and Loading Function

Having some trouble with my JQuery code on mobile devices. The drop down menu isn't showing up on an iPhone, the load function isn't working to display the additional PHP page on a Samsung Edge 7, and the drop down doesn't seem to be functio ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

Looking for regex to extract dynamic category items in node.js

Working on node.js with regex, I have accomplished the following tasks: Category 1.2 Category 1.3 and 1.4 Category 1.3 to 1.4 CATEGORY 1.3 The current regex is ((cat|Cat|CAT)(?:s\.|s|S|egory|EGORY|\.)?)( |\s)?((\w+)?([. ...

Tips on efficiently compressing JSON data in order to receive it using the bodyParser.json method

I am looking to compress a JSON file before sending it to my server. I want to handle the compression in the browser by utilizing an explainer and then pass it to the bodyParser.json middleware. The client-side function would look something like this: e ...

Why MongoDB's Push Operation Using Positional Operator isn't Functioning

In the 'users' collection, I have a document with the following data: { "_id" : "388179687996974", "matches" : [ { "userId" : "1495728740672094", "choice" : false, "dates" : [], "d ...

When the caret triangle is upside down, it indicates that a drop-down menu is available even when the

I am facing an issue with a dropdown list where the triangle indicator is incorrectly displayed: https://i.stack.imgur.com/L4NBW.png Both images show that the arrows are in reverse direction, and I am struggling to identify the cause of this problem. He ...