phpnerd
phpnerd

Reputation: 926

How to use aws s3 image url in node js lambda?

I am trying to use aws s3 image in lambda node js but it throws an error 'no such file or directory'. But I have made that image as public and all permissions are granted.

fs = require('fs');
exports.handler = function( event, context ) {

         var img = fs.readFileSync('https://s3-us-west-2.amazonaws.com/php-7/pic_6.png');
         res.writeHead(200, {'Content-Type': 'image/png' });
         res.end(img, 'binary');
};

Upvotes: 0

Views: 1656

Answers (3)

user8400905
user8400905

Reputation:

To get a file from S3, you need to use the path that S3 give you. The base path is https://s3.amazonaws.com/{your-bucket-name}/{your-file-name}.

On your code, you must replace the next line:

var img = fs.readFileSync('https://s3.amazonaws.com/{your-bucket-name}/pic_6.png');

If don't have a bucket, you should to create one to give permissions.

Upvotes: 0

user818510
user818510

Reputation: 3622

There are multiple things wrong with your code.

fs is a core module used for file operations and can't be used to access S3.

You seem to be using express.js code in your example. In lambda, there is no built-in res defined(unless you define it yourself) that you can use to send response.

You need to use the methods on context or the new callback mechanism. The context methods are used on the older lambda node version(0.10.42). You should be using the newer node version(4.3.2 or 6.10) which return response using the callback parameter.

It seems like you are also using the API gateway, so assuming that, I'll give a few suggestions. If the client needs access to the S3 object, these are some of your options:

  • Read the image from S3 using the AWS sdk and return the image using the appropriate binary media type. AWS added support for binary data for API gateway recently. See this link OR
  • Send the public S3 URL to client in your json response. Consider whether the S3 objects need to be public. OR
  • Use the S3 sdk to generate pre-signed URLs that are valid for a configured duration back to the client.

I like the pre-signed URL approach. I think you should check that out. You might also want to check the AWS lambda documentation

Upvotes: 0

Edgar
Edgar

Reputation: 1313

fs is node js file system core module. It is for writing and reading files on local machine. That is why it gives you that error.

Upvotes: 2

Related Questions