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()
Output
foobar
received: abc
received: xyz
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()
}
Output
foobar
received: abc
received: xyc
当前内容版权归 miguelmota 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 miguelmota .