How do you write to the file system of an aws lambda instance? How do you write to the file system of an aws lambda instance? node.js node.js

How do you write to the file system of an aws lambda instance?


Modifying your code into the Lambda template worked for me. I think you need to assign a function to exports.handler and call the appropriate context.succeed() or context.fail() method. Otherwise, you just get generic errors.

var fs = require("fs");exports.handler = function(event, context) {    fs.writeFile("/tmp/test.txt", "testing", function (err) {        if (err) {            context.fail("writeFile failed: " + err);        } else {            context.succeed("writeFile succeeded");        }    });};


So the answer lies in the context.fail() or context.succeed() functions. Being completely new to the world of aws and lambda I was ignorant to the fact that calling any of these methods stops execution of the lambda instance.

According to the docs:

The context.succeed() method signals successful execution and returns a string.

By eliminating these and only calling them after I had run all the code that I wanted, everything worked well.


I ran into this, and it seems like AWS Lambda may be using an older (or modified) version of fs. I figured this out by logging the response from fs.writeFile and noticed it wasn't a promise.

To get around this, I wrapped the call in a promise:

var promise = new Promise(function(resolve, reject) {    fs.writeFile('/tmp/test.txt', 'testing', function (err) {        if (err) {            reject(err);        } else {            resolve();        }    });});

Hopefully this helps someone else :hug-emoji: