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);
};
Navid Yousefzai
  • 141
  • 1
  • 9

2 Answers2

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)

Thales Minussi
  • 6,965
  • 1
  • 30
  • 48
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'
     };
   }
};
ttulka
  • 10,309
  • 7
  • 41
  • 52