how to run system command in node js code example
Example 1: node run shell command
const { exec } = require("child_process");
exec("ls -la", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
Example 2: node run command
const { spawn } = require('child_process');
const dir = spawn('cmd', ['/c', 'dir']);
dir.stdout.on('data', data => console.log(`Stdout: ${data}`));
dir.stderr.on('data', data => console.log(`Stderr: ${data}`));
dir.on('close', code => console.log(`Exit code: ${code}`));
const { spawnSync } = require( 'child_process' );
const dir = spawnSync('cmd', ['/c', 'dir']);
console.log(`Stdout: ${dir.stdout.toString()}`);
console.log(`Stderr: ${dir.stderr.toString()}`);