Sometimes, we want to execute shell command in JavaScript.
In this article, we’ll look at how to execute shell command in JavaScript.
How to execute shell command in JavaScript?
To execute shell command in JavaScript, we can use the exec
function.
For instance, we write
const { exec } = require("child_process");
exec("cat *.js bad_file | wc -l", (error, stdout, stderr) => {
console.log("stdout: " + stdout);
console.log("stderr: " + stderr);
if (error !== null) {
console.log("exec error: " + error);
}
});
to call the child_process
module’s exec
function.
We call it with the command we want to run in a string.
The 2nd argument is a callback that gets the output from the command.
The stdout
variable has the standard output output.
And stderr
has the standard error output.
error
has the errors is there’s any.
Conclusion
To execute shell command in JavaScript, we can use the exec
function.