To execute bash command in Node.js and get exit code, we call exec
.
For instance, we write
const dir = exec("ls -la", (err, stdout, stderr) => {
console.log(stdout);
});
dir.on("exit", (code) => {
console.log(code);
});
to call exec
to run the ls -la
command.
We get the output from stdout
in the callback.
Then we call dir.on
to listen for the exit
event.
And we get the exit code from code
in the callback.