streams
Examples of reading and writing streams
# Node.js
const { Readable, Writable } = require("stream");
const inStream = new Readable();
inStream.push(Buffer.from("foo"));
inStream.push(Buffer.from("bar"));
inStream.push(null); // end stream
inStream.pipe(process.stdout);
const outStream = new Writable({
write(chunk, encoding, callback) {
console.log("received: " + chunk.toString("utf8"));
callback();
},
});
outStream.write(Buffer.from("abc"));
outStream.write(Buffer.from("xyz"));
outStream.end();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Output
foobar
received: abc
received: xyz
1
2
3
2
3
# Go
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"runtime"
)
func main() {
inStream := new(bytes.Buffer)
w := bufio.NewWriter(inStream)
_, err := w.Write([]byte("foo"))
if err != nil {
panic(err)
}
_, err = w.Write([]byte("bar"))
if err != nil {
panic(err)
}
err = w.Flush()
if err != nil {
panic(err)
}
inStream.WriteTo(os.Stdout)
fmt.Print("\n")
outStream := new(bytes.Buffer)
outStream.Write([]byte("abc\n"))
outStream.Write([]byte("xyc\n"))
piper, pipew := io.Pipe()
go func() {
sc := bufio.NewScanner(piper)
for sc.Scan() {
fmt.Println("received: " + sc.Text())
}
if err := sc.Err(); err != nil {
panic(err)
}
os.Exit(0)
}()
go func() {
defer pipew.Close()
io.Copy(pipew, outStream)
}()
defer runtime.Goexit()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Output
foobar
received: abc
received: xyc
1
2
3
2
3
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22