Executing shell commands from Node.js

submited by
Style Pass
2022-07-06 18:00:03

Module 'node:child_process' has a function for executing shell commands (in spawned child processes) that comes in two versions:

We’ll first explore spawn() and then spawnSync(). We’ll conclude by looking at the following functions that are based on them and relatively similar:

The code shown in this blog post runs on Unix, but I have also tested it on Windows – where most of it works with minor changes (such as ending lines with '\r\n' instead of '\n').

Assertions: assert.equal() for primitive values and assert.deepEqual() for objects. The necessary import is never shown in the examples:

Function Readable.toWeb() converts Node’s native stream.Readable to a web stream (an instance of ReadableStream). It is explained in the blog post on web streams for more information. Readable is always imported in the examples.

The asynchronous function readableStreamToString() consumes a readable web stream and returns a string (wrapped in a Promise). It is explained in the blog post on web streams](https://2ality.com/2022/06/web-streams-nodejs.html#example%3A-assembling-a-string-with-the-contents-of-a-readablestream). This function is assumed to simply exist in the examples.

Leave a Comment