简体   繁体   中英

Get result of spawning child process in Node.js

How do I execute a child process and get the resulting exit code and output (stdout, stderr)?

Something like

let spawnResult = Node.Child_process.spawnSync("ls");

Js.log("Exit code: " ++ spawnResult.status);

Js.log("Stdout: " ++ spawnResult.stdout);

Js.log("Stderr: " ++ spawnResult.stderr);

Unfortunately this results in a compile error:

Unbound record field status

There are several issues here:

  1. spawnResult is actually an abstract type, and will have to be cast to a Js Object using Node.Child_process.readAs before being used.

  2. JavaScript Object fields are accessed using the ## operator. . is reserved for accessing record fields (and # is for plain OCaml objects).

In addition, ++ will only concatenate strings, while status is an int , and stdout and stderr are string_buffer s. You therefore need to either use string interpolation, which converts to string automatically, manually convert them before concatenating, or use Js.log2 :

Using string interpolation:

let status = Node.Child_process.readAs(spawnResult)##status;
Js.log({j|Exit code: $status|j});

Using manual string conversion

Js.log("Exit code: " ++ string_of_int(Node.Child_process.readAs(spawnResult)##status));

Using Js.log2 :

Js.log2("Exit code: ", Node.Child_process.readAs(spawnResult)##status);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM