2

I am trying to execute a shell command to migrate from the AWS lambda. The idea is that whenever we need to run the migration, we will call the lambda via AWS CLI. I am unable to make it run. The command to run migration never gets executed and it's always response with null. Any help would be greatly appreciated.

This is the code I have :

const exec = require("child_process").exec;
const { okResponse, errorResponse } = require('./response');

exports.handler = async (event) => {
    exec("node ./node_modules/db-migrate/bin/db-migrate up --config=./database.json", (error, stdout, stderr) => {
        if (error) {
            console.error(`error: ${error.message}`);
            return errorResponse(500, 'Error running migration.');
        }
        if (stderr) {
            console.log(`stderr: ${stderr}`);
            return errorResponse(500, 'Error running migration.');
        }
        console.log(`stdout: ${stdout}`);
        return okResponse(200, 'Migration successfully.');
    });
}
2
  • What happens when you put await before your command execution line await exec("node ./node_modules/db-migrate/bin/db-migrate up Commented Oct 28, 2020 at 9:36
  • Also how are you calling the function from CLI? Commented Oct 28, 2020 at 9:39

1 Answer 1

6

My guess is that because you are using async lambda handler your function finishes before exec has a chance to even run. Therefore, you could use promise, as shown in the linked docs, to solve this issue.

An example would be:

const exec = require("child_process").exec;
const { okResponse, errorResponse } = require('./response');

exports.handler = async (event) => {


    const promise = new Promise(function(resolve, reject) {
   
        exec("node ./node_modules/db-migrate/bin/db-migrate up --config=./database.json", (error, stdout, stderr) => {
            if (error) {
                console.error(`error: ${error.message}`);
                return errorResponse(500, 'Error running migration.');
            }
            if (stderr) {
                console.log(`stderr: ${stderr}`);
                return errorResponse(500, 'Error running migration.');
            }
            console.log(`stdout: ${stdout}`);
            return okResponse(200, 'Migration successfully.');
          })
    })

   return promise
}

Please note that I haven't run the code, and further changes may be required to make it work correctly.

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

1 Comment

Sorry for the late reply. I already solved it. And yes, a Promise was what I needed. Your answer matches the solution. I am going to accept your answer. Thank you for your time. Cheers

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.