Hey everyone! Does anybody knows function like os.system(command)
to run shell command in JavaScript?
I make a function to run any command in shell with child_proccess:
const { spawn,execFile } = require('child_proccess')
const system = (command) => {
spawn("touch",[__dir+"spawn.sh"])
spawn("write",[command,__dir+"spawn.sh"])
execFile(__dir+"spawn.sh", (error,stdout,stderr) => {
console.log(stdout)
})
spawn("rm",[__dir+"spawn.sh"])
}
2 Likes
Could you just do this?
const { exec } = require("child_process");
const system = (command) => {
exec(command, (err, stdout, stderr) => {});
}
Or if you wanted to be able to get the output from the function, do this.
const { exec } = require("child_process");
const system = (command) => {
return new Promise((resolve, reject) => {
exec(command, (err, stdout, stderr) => {
if (err) reject(err);
else resolve(stdout);
});
});
}
3 Likes
Thanks. But I have a question: exec()
function takes 2 arguments or 2rd argument is optional?
I think it is optional so the first one could be condensed into just this
const { exec } = require("child_process");
// kinda redundant
const system = (command) => exec(command);
system("echo Hello World!");
// instead I would just use the default exec command like this
exec("echo Hello World!");
2 Likes
Ok, now I know how to run shell commands in JS. Thanks!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.