streams


Examples of reading and writing streams

Node.js

  1. const { Readable, Writable } = require('stream')
  2. const inStream = new Readable()
  3. inStream.push(Buffer.from('foo'))
  4. inStream.push(Buffer.from('bar'))
  5. inStream.push(null) // end stream
  6. inStream.pipe(process.stdout)
  7. const outStream = new Writable({
  8. write(chunk, encoding, callback) {
  9. console.log('received: ' + chunk.toString('utf8'))
  10. callback()
  11. }
  12. })
  13. outStream.write(Buffer.from('abc'))
  14. outStream.write(Buffer.from('xyz'))
  15. outStream.end()

Output

  1. foobar
  2. received: abc
  3. received: xyz

Go

  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "os"
  8. "runtime"
  9. )
  10. func main() {
  11. inStream := new(bytes.Buffer)
  12. w := bufio.NewWriter(inStream)
  13. _, err := w.Write([]byte("foo"))
  14. if err != nil {
  15. panic(err)
  16. }
  17. _, err = w.Write([]byte("bar"))
  18. if err != nil {
  19. panic(err)
  20. }
  21. err = w.Flush()
  22. if err != nil {
  23. panic(err)
  24. }
  25. inStream.WriteTo(os.Stdout)
  26. fmt.Print("\n")
  27. outStream := new(bytes.Buffer)
  28. outStream.Write([]byte("abc\n"))
  29. outStream.Write([]byte("xyc\n"))
  30. piper, pipew := io.Pipe()
  31. go func() {
  32. sc := bufio.NewScanner(piper)
  33. for sc.Scan() {
  34. fmt.Println("received: " + sc.Text())
  35. }
  36. if err := sc.Err(); err != nil {
  37. panic(err)
  38. }
  39. os.Exit(0)
  40. }()
  41. go func() {
  42. defer pipew.Close()
  43. io.Copy(pipew, outStream)
  44. }()
  45. defer runtime.Goexit()
  46. }

Output

  1. foobar
  2. received: abc
  3. received: xyc