Comparing options, prior to refactoring the broken flow control in my Gulpfile.
Asynchronous, optionally runs a callback function.
Spawns a shell then executes the command within that shell, buffering any generated output.
callback <Function>
called with the output when process terminates.Returns:
<ChildProcess>
~ Node.js docs
// Example
const { exec } = require( 'child_process' );
function execTest() {
exec( 'echo "exec test"', ( error, stdout, stderr ) => {
if ( error ) {
console.error( error );
return;
}
console.log( stdout );
console.error( stderr );
} );
}
execTest()
Spawn in computing refers to a function that loads and executes a new child process.
Creating a new subprocess requires enough memory in which both the child process and the current program can execute.
Any command that you would normally type into terminal, e.g.
echo "hello world"
If a callback function is provided, it is called with the arguments (
error
,stdout
,stderr
)The
stdout
andstderr
arguments passed to the callback will contain thestdout
andstderr
output of the child process. By default, Node.js will decode the output as UTF-8 and pass strings to the callback.~ Node.js docs
When the process is complete the callback will fire.
stdout
refers to a message output to the 'standard output' location. In the terminal, standard output defaults to the user's screen.
Synchronous, no callback option.
The
child_process.execSync()
method is generally identical tochild_process.exec()
with the exception that the method will not return until the child process has fully closed.Returns:
<Buffer> | <string>
The stdout from the command.~ Node.js docs
// Example
const { execSync } = require( 'child_process' );
function execSyncTest() {
const execSyncBuffer = execSync( 'echo "execSync test"' );
console.log( execSyncBuffer.toString() );
}
execSyncTest();
Synchronous scripts block the Event Loop / main thread.
x-node-exec.js
shows that the execSync
functions are run first, before any of the other test functions.
An important difference between exec
and execSync
is that the latter returns a Buffer
.
Node's Buffer
class is a mechanism for reading or manipulating streams of binary data.
In a Buffer
the numbers are shown in hexidecimal format.
When we extract string data from a Buffer
, we need to convert it into a string, using String.prototype.toString()
.
Asynchronous, returns a promise.
util.promisify( original )
Takes a function following the common error-first callback style, i.e. taking an
(err, value) => ...
callback as the last argument, and returns a version that returns promises.~ Node.js docs
// Example
const util = require( 'util' );
const { exec } = require( 'child_process' );
const execPromise = util.promisify( exec );
async function execPromiseTest() {
const { stdout, stderr } = await execPromise( 'echo "execPromise test"' );
console.log( stdout );
console.error( stderr );
}
execPromiseTest();
Output: