gaurav gaurav - 2 months ago 19
Node.js Question

reading a packaged file in aws lambda package

I have a very simple node lambda function which reads the contents of packaged file in it. I upload the code as zip file. The directory structure is as follows.

index.js
readme.txt


Then have in my index.js file:

fs.readFile('/var/task/readme.txt', function (err, data) {
if (err) throw err;
});


I keep getting the following error NOENT: no such file or directory, open
'/var/task/readme.txt'.


I tried ./readme.txt also.

What am I missing ?

Answer Source

Try this, it works for me:

'use strict'

let fs = require("fs");
let path = require("path");

exports.handler = (event, context, callback) => {
        // To debug your problem
        console.log(path.resolve("./readme.txt"));

        // Solution is to use absolute path using `__dirname`
        fs.readFile(__dirname +'/readme.txt', function (err, data) {
            if (err) throw err;
        });
};

to debug why your code is not working, add below link in your handler

console.log(path.resolve("./readme.txt"));

On AWS Lambda node process might be running from some other folder and it looks for readme.txt file from that folder as you have provided relative path, solution is to use absolute path.