I am in the process of porting a CLI library from Ruby over to Node.js. In my code I execute several third party binaries when necessary. I am not sure how best to accomplish this in Node.
Here's an example in Ruby where I call PrinceXML to convert a file to a PDF:
cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf")
What is the equivalent code in Node?
I just wrote a Cli helper to deal with Unix/windows easily.
Javascript:
Typescript original source file:
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
child_process.exec
: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
child_process.execSync
:As well as
child_process.spawnSync
: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 need to use handle process I/O with streams, such as when you are expecting large amounts of output, use
child_process.spawn
:If you are executing a file rather than a command, you might want to use
child_process.execFile
, which parameters which are almost identical tospawn
, but has a fourth callback parameter likeexec
for retrieving output buffers. That might look a bit like this:As of v0.11.12, Node now supports synchronous
spawn
andexec
. 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 ofChildProcess
.Node JS
v11.5.0
, LTSv10.14.2
, andv8.14.1
--- Dec 2018Async and proper method (Unix):
Async method (Windows):
Sync:
From Node.js v11.5.0 Documentation
The same goes for Node.js v10.14.2 Documentation and Node.js v8.14.1 Documentation
You are looking for child_process.exec
Here is the example:
If you want something that closely resembles the top answer but is also synchronous then this will work.
Since version 4 the closest alternative is
child_process.execSync
method:Note that this method blocks event loop.