For demonstration purposes, we’ll execute the command
dir
, which displays a direc‐
tory listing (while Unix users are more familiar with
ls
,
dir
is aliased to
ls
on most
Unix systems):
const
exec
=
require
(
'child_process'
).
exec
;
exec
(
'dir'
,
function
(
err
,
stdout
,
stderr
) {
if
(
err
)
return
console
.
error
(
'Error executing "dir"'
);
stdout
=
stdout
.
toString
();
// convert Buffer to string
console
.
log
(
stdout
);
stderr
=
stderr
.
toString
();
if
(
stderr
!==
''
) {
console
.
error
(
'error:'
);
console
.
error
(
stderr
);
}
});
Because
exec
spawns a shell, we don’t need to provide the path to where the
dir
exe‐
cutable lives. If we were invoking a specific program that’s not generally available
from your system’s shell, you would need to provide a full path to the executable.
The callback that gets invoked receives two
Buffer
objects for
stdout
(the normal
output of a program) and
stderr
(error output, if any). In this example, since we
don’t expect any output on
stderr
, we check first to see if there was any error output
before printing it out.
exec
takes an optional
options
object, which allows us to specify things like the
working directory, environment variables, and more. See the
for more information.
Note the way we import exec. Instead of importing child_process
with const child_process = require('child_process'), and
then calling exec as child_process.exec, we simply alias exec
right away. We could do it either way, but the way we’ve done it is
quite common.
Streams
The concept of a stream is an important one in Node. A stream is an object that deals
with data—as the name implies—in a stream (the word stream should make you
think of flow, and because flow is something that happens over time, it makes sense
that it would be asynchronous).
Streams can be read streams, write streams, or both (called duplex streams). Streams
make sense whenever the flow of data happens over time. Examples might be a user
typing at a keyboard, or a web service that has back-and-forth communication with a
client. File access, too, often uses streams (even though we can also read and write
Streams | 295