For even newer version of Node.js (v8.1.4), the events and calls are similar or identical to older versions, but it's encouraged to use the standard newer language features. Examples:
For buffered, non-stream formatted output (you get it all at once), use
You can also use it with Promises:
If you wish to receive the data gradually in chunks (output as a stream), use child_process.spawn:
Both of these functions have a synchronous counterpart. An example for
As well as
Note: The following code is still functional, but is primarily targeted at users of ES5 and before.
The module for spawning child processes with Node.js is well documented in the documentation (v5.0.0). To execute a command and fetch its complete output as a buffer, use child_process.exec:
If you are executing a file rather than a command, you might want to use
child_process.execFile, which parameters which are almost identical to spawn, but has a fourth callback parameter like exec for retrieving output buffers. That might look a bit like this:
As of v0.11.12, Node now supports synchronous spawn and exec. All of the methods described above are asynchronous, and have a synchronous counterpart. Documentation for them can be found here. While they are useful for scripting, do note that unlike the methods used to spawn child processes asynchronously, the synchronous methods do not return an instance of ChildProcess.