1// You can use 'exec' this way
2
3const { exec } = require("child_process");
4
5exec("ls -la", (error, stdout, stderr) => {
6 if (error) {
7 console.log(`error: ${error.message}`);
8 return;
9 }
10 if (stderr) {
11 console.log(`stderr: ${stderr}`);
12 return;
13 }
14 console.log(`stdout: ${stdout}`);
15});
16
1// Async
2const { exec } = require("child_process"); // import { exec } from "child_process"
3
4exec("ls -la", (error, stdout, stderr) => {
5 if (error) {
6 console.log(`error: ${error.message}`);
7 return;
8 }
9 if (stderr) {
10 console.log(`stderr: ${stderr}`);
11 return;
12 }
13 console.log(`stdout: ${stdout}`);
14});
15
16// Sync
17const { execSync } = require("child_process"); // import { execSync } from "child_process"
18
19const result = execSync("ls -la")
20console.log(result.toString())
1const { spawn } = require('child_process');
2const ls = spawn('ls', ['-lh', '/usr']);
3
4ls.stdout.on('data', (data) => {
5 console.log(`stdout: ${data}`);
6});
7
8ls.stderr.on('data', (data) => {
9 console.error(`stderr: ${data}`);
10});
11
12ls.on('close', (code) => {
13 console.log(`child process exited with code ${code}`);
14});
15
1var child = require('child_process').exec('python celulas.py')
2child.stdout.pipe(process.stdout)
3child.on('exit', function() {
4 process.exit()
5})
1// OR...
2const { exec, spawn } = require('child_process');
3exec('my.bat', (err, stdout, stderr) => {
4 if (err) {
5 console.error(err);
6 return;
7 }
8 console.log(stdout);
9});
10
11// Script with spaces in the filename:
12const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });
13// or:
14exec('"my script.cmd" a b', (err, stdout, stderr) => {
15 // ...
16});
17