Last active
June 2, 2022 21:49
-
-
Save rauschma/74abf3443040874443cdf02432dac06a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Readable} from 'node:stream'; | |
import {TextDecoderStream} from 'node:stream/web'; | |
import {spawn} from 'node:child_process'; | |
const childProcess = spawn( | |
'echo', ['hello world'], | |
{ | |
stdio: ['ignore', 'pipe', 'inherit'], | |
} | |
); | |
const nodeReadable = childProcess.stdout; | |
// Reading from `nodeReadable` (e.g. via async iteration) produces buffers. | |
// (I couldn’t find a way to change that). | |
// That leads to `Readable.toWeb(nodeReadable)` creating a stream that produces | |
// instances of `Uint8Array`. Hence the `TextDecoderStream`! | |
const webReadable = Readable.toWeb(nodeReadable).pipeThrough(new TextDecoderStream('utf-8')); | |
for await (const chunk of webReadable) { | |
console.log(chunk); | |
} |
@manwey You need to run Node.js v17.0.0 or later: https://nodejs.org/api/stream.html#streamreadabletowebstreamreadable
The goal of this experiment was to use the new web streams API: https://nodejs.org/api/webstreams.html
Thanks @rauschma I will give a try.
Did you try my code to get utf8 strings from the buffers?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried your code but get this error:
TypeError: Readable.toWeb is not a function
Try using this code:
`
nodeReadable.setEncoding('utf8');
`
or also:
for await (const chunk of nodeReadable) { console.log(chunk.toString()); // hello world }