node v6.17.1
version: 1.0.0
spawn() spawns a new process using the given command, with any command line arguments passed into an array. Unlike exec(), no extra shell gets spawned, so that output is not buffered, but caught via event handlers.
// Require necessary modules const childProcess = require('child_process'); const os = require('os'); // Show OS/kernel version console.log(`Kernel version: ${os.release()}`); // Show current working directory (CWD) console.log(`CWD: ${process.cwd()}`);
Now creating instance of child_process.spawn() Goal is to show the contents of the root directory using native 'ls'-command.
const ls = childProcess.spawn('ls', ['-lh', '/']);
Listening for console output events below:
ls.stdout.on('data', output => console.log(`Info: ${output}`)); // Normal output ls.stderr.on('data', err => console.error(`Error: ${err}`)); // Error output
Listening for 'close' event below, this event is fired whenever the child process was closed/killed.
ls.on('close', code => console.log(`Child process closed with code ${code}`));

no comments

    sign in to comment