1

I am trying to write and read to /temp dir in lambda during function execution, I know the best way would be to use S3, but for this project, I have to use node file system

const fs = require('fs');


exports.handler = async (event) => {

const path = '/tem/hi.json';

const write = (file) => {

 fs.writeFile(file, "Hello World!", function(err) {

 if (err) return console.log(err);
 return {
 statusCode:200,
 body:JSON.stringify('data was written')
       };
    });
 };

 return write(path);
};
3
  • 1
    Are you getting an error? What's the issue? Commented Mar 27, 2019 at 19:03
  • when I try to read it I get a Response: null Commented Mar 27, 2019 at 19:04
  • 1
    The directory name is /tmp - your code isn't showing that. Commented Mar 27, 2019 at 19:15

2 Answers 2

5

You have a typo on your file path.

Change

const path = '/tem/hi.json';

to

const path = '/tmp/hi.json';

Also, fs.writeFile is an asynchronous operation. Promisify it so you can await on it:

 const write = file => {
    return new Promise((res, rej) => {
        fs.writeFile(file, JSON.stringify({ message: 'hello world' }), (err) => {
            if (err) {
                return rej(err)
            }
            return res({
                statusCode: 200,
                body: JSON.stringify({message: 'File written successfully'})
            })
        })
    })
}

Finally, on your client (last line of your handler), just invoke it like this:

return await write(path)

Sign up to request clarification or add additional context in comments.

Comments

1

fs.writeFile is an asynchronous operation, so the lambda ends before it finishes. You can use fs.writeFileSync to block the lambda execution until the file is sucessfuly written:

const write = (file) => {
   try {
     fs.writeFileSync(file, "Hello World!");
     return {
       statusCode: 200,
       body: 'data was written'
     };    
   } catch (err) {
     console.log(err);
     return {
       statusCode: 500,
       body: 'data was not written'
     };
   }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.