1

I would like to read the content of a .txt file stored within an s3 bucket.

I tried :

var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {Bucket: 'My-Bucket', Key: 'MyFile.txt'};
var s3file = s3.getObject(params)

But the s3file object that i get does not contain the content of the file.

Do you have an idea on what to do ?

Ranisterio
  • 107
  • 1
  • 6
  • 1
    Does this answer your question? [Read file from aws s3 bucket using node fs](https://stackoverflow.com/questions/27299139/read-file-from-aws-s3-bucket-using-node-fs) – mtkopone May 13 '20 at 13:01

2 Answers2

1

Agree with zishone and here is the code with exception handling:

var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {Bucket: 'My-Bucket', Key: 'MyFile.txt'};

s3.getObject(params , function (err, data) {

    if (err) {
        console.log(err);
    } else {
        console.log(data.Body.toString());
    }

})
SkrewEverything
  • 2,393
  • 1
  • 19
  • 50
  • Thank you, it does not raise an error but it does not print someting in the console. Why ? How to get the result ? – Ranisterio May 13 '20 at 15:29
  • This thing works perfectly for me. Post your lambda and the role you are using, and the bucket policy if you have. Here is my lmbda var AWS = require('aws-sdk'); var s3 = new AWS.S3(); exports.handler = (event, context, callback) => { var s3 = new AWS.S3({apiVersion: '2006-03-01'}); var params = {Bucket: 'bucket-name', Key: 'test.txt'}; s3.getObject(params , function (err, data) { if (err) { console.log(err); } else { console.log("TEXT FROM FILE: " + data.Body.toString()); } }) }; – ExpertCoder May 13 '20 at 17:41
  • I use a lambda full acces role, with the code you sent. It does not print anything in the console. – Ranisterio May 14 '20 at 08:33
0

According to the docs the contents of your file will be in the Body field of the result and it will be a Buffer.

And another problem there is that s3.getObject( should have a callback.

s3.getObject(params, (err, s3file) => {
    const text = s3file.Body.toString();
})
zishone
  • 1,196
  • 1
  • 9
  • 11