|
1 | 1 | /* eslint-disable no-console */ |
2 | 2 |
|
3 | | -import * as lp from 'it-length-prefixed' |
4 | | -import map from 'it-map' |
5 | | -import { pipe } from 'it-pipe' |
6 | | -import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' |
| 3 | +import { lpStream } from '@libp2p/utils' |
7 | 4 | import { toString as uint8ArrayToString } from 'uint8arrays/to-string' |
8 | 5 |
|
9 | 6 | export function stdinToStream (stream) { |
10 | | - // Read utf-8 from stdin |
11 | | - process.stdin.setEncoding('utf8') |
12 | | - pipe( |
13 | | - // Read from stdin (the source) |
14 | | - process.stdin, |
15 | | - // Turn strings into buffers |
16 | | - (source) => map(source, (string) => uint8ArrayFromString(string)), |
17 | | - // Encode with length prefix (so receiving side knows how much data is coming) |
18 | | - (source) => lp.encode(source), |
19 | | - // Write to the stream (the sink) |
20 | | - stream.sink |
21 | | - ) |
| 7 | + // Encode with length prefix (so receiving side knows how much data is coming) |
| 8 | + const lp = lpStream(stream) |
| 9 | + |
| 10 | + process.stdin.addListener('data', (buf) => { |
| 11 | + lp.write(buf) |
| 12 | + }) |
22 | 13 | } |
23 | 14 |
|
24 | 15 | export function streamToConsole (stream) { |
25 | | - pipe( |
26 | | - // Read from the stream (the source) |
27 | | - stream.source, |
28 | | - // Decode length-prefixed data |
29 | | - (source) => lp.decode(source), |
30 | | - // Turn buffers into strings |
31 | | - (source) => map(source, (buf) => uint8ArrayToString(buf.subarray())), |
32 | | - // Sink function |
33 | | - async function (source) { |
34 | | - // For each chunk of data |
35 | | - for await (const msg of source) { |
36 | | - // Output the data as a utf8 string |
37 | | - console.log('> ' + msg.toString().replace('\n', '')) |
38 | | - } |
| 16 | + const lp = lpStream(stream) |
| 17 | + |
| 18 | + Promise.resolve().then(async () => { |
| 19 | + while (true) { |
| 20 | + // Read from the stream |
| 21 | + const message = await lp.read() |
| 22 | + |
| 23 | + // Output the data as a utf8 string |
| 24 | + console.log('> ' + uint8ArrayToString(message.subarray()).replace('\n', '')) |
39 | 25 | } |
40 | | - ) |
| 26 | + }) |
41 | 27 | } |
0 commit comments