Core Streams

In notebook:
FrontEndMasters Networking and Streams
Created at:
2017-09-24
Updated:
2017-11-08
Tags:
backend Node JS JavaScript Fundamentals

core streams in node

many of the APIs in node core provide stream interfaces:

  • fs.createReadStream()
  • fs.createWriteStream()
  • process.stdin, process.stderr ☛ stderr (you can put errors in the terminal)
  • ps.stdin, ps.stdout, ps.stderr
  • net.connect(), tls.connect()
  • net.createServer(function (stream) {})
  • tls.createServer(opts, function (stream) {}) ☛ for ssl connections (you need certificates)

...

You can create child processes in NodeJS.

  //	****		ps.js		****
var spawn = require('child_process').spawn

var ps = spawn('grep', ['potato'])
ps.stdout.pipe(process.stdout)
ps.stdin.write('chees\n')
ps.stdin.write('carrot\n')
ps.stdin.write('carrot potatoes\n')
ps.stdin.write('potato!\n')
ps.stdin.end()

So every time on this child process, I put the string "potato" it will return it.

Now, $ node ps.js returns:

carrot potatoes
potato!

http core streams

// req: readable, res: writable
http.createServer(function (req, res) {})

// req: writable, res: readable
var req = http.request(opts, function (res) {})