1

In node.js I'm making call a script with exec from child_process.

When in the closed state I want to check if there was any error so I can return it however I can't seem to access error in the second function on().

Could someone kindly explain how I can pass it along.

exec('myScript.sh',
        (error: any, stdout: any, stderr: any) => { }).on('close', () => {
            console.log(error)
        })

Thanks.

1 Answer 1

1

You need to store it outside of the callback function. If you look at the ES5 equivalent:

exec("myScript.sh", function(error, stdout, stderr) {
    // Do nothing
}).on("close", function() {
    // Cannot access error here
});

You can see that the scope of error is local to the anonymous callback function that is exec's second argument. You can access it within the onclose callback function by storing it with a scope accessible to that function like so:

let execError = "";

exec("myScript.sh", function(error, stdout, stderr) {
    execError = error;
}).on("close", function() {
    console.log(execError);
});

Or in your original notation (ES6):

let execError: any = "";

exec("myScript.sh", (error: any, stdout: any, stderr: any) => { 
    execError = error; 
}).on("close", () => { 
    console.log(execError); 
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.