I want to build a nodejs application which will do some automatic work for me . But I want to know if I can execute terminal commands in nodejs . Is there any module which will be helpful to access command line interface ? Suppose I want to run this command code .
or ifconfig
or cd
. So how can I do this from nodejs application ?
I know I can run nodejs from my terminal But I want to access terminal and do whatever I want .like installing other softwares from terminal Like executing 'apt install package-name'
Asked
Active
Viewed 441 times
-2

Hasnath abdullah aknd
- 302
- 3
- 10
-
1https://nodejs.org/api/child_process.html#child_process_child_process – zero298 Jun 25 '21 at 23:22
-
1duplicate of [execute-a-command-line-binary-with-node-js](https://stackoverflow.com/questions/20643470/execute-a-command-line-binary-with-node-js) – Divy Jun 25 '21 at 23:45
1 Answers
1
So what you want is a portable method of running system specific functionality. Thankfully, nodejs has a module to do this called the child_process module. For more specific information you can glance at the linked documentation, but a basic example goes like this:
const { spawn } = require('child_process');
// Here we make the call making sure to list the command first and the arguments as the next parameter in a list
const diff = spawn('diff', ["texta.txt", "textb.txt"])
// We can also log the output of this function with
diff.stdout.on('data', (data) => {
console.log(data.toString());
});
// or we can log the exit code with
diff.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});

zbuster05
- 11
- 2