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.
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.