nodejs / readable-stream

Node-core streams for userland
https://nodejs.org/api/stream.html
Other
1.03k stars 227 forks source link

Streams cookbook #336

Closed mafintosh closed 2 years ago

mafintosh commented 6 years ago

Bunch of examples for writing streams.

A series of examples on how to write different kind of pipelines etc.

indexzero commented 6 years ago

Hot take on TOC for this:

mafintosh commented 6 years ago

Thoughts:

Cookbook example. A stream that writes first to a tmp file, then to a normal file.

const stream = require('readable-stream')

const fd = fs.openSync('file.tmp', 'w')
const ws = stream.Writable({
  write: function (data, enc, cb) {
    write(fd, data, cb)
  },
  // using the final method we can make sure the 'finish' event
  // happens *after* the file has been renamed, which makes composition
  // a lot easier.
  final: function (cb) {
    fs.close(fd, function (err) {
      if (err) return cb(err)
      fs.rename('file.tmp', 'file', cb)
    })
  }
})

// a simple function that writes all data to a file
function write (fd, data, cb) {
  fs.write(fd, data, 0, data.length, function (err, wrote) {
    if (err) return cb(err)
    data = data.slice(wrote)
    if (data.length) write(fd, data, cb)
    else cb()
  })
}

I think the cookbook should just be a bunch of those

mafintosh commented 6 years ago

Another example:

const duplexify = require('duplexify')
const http = require('http')

// duplex http stream
function request (opts) {
  const stream = duplexify()
  const req = http.request(opts, function (res) {
    stream.setReadable(res)
  })
  stream.setWritable(req)
  return stream
}
mcollina commented 6 years ago

cc @amiller-gh - this is the guide we have been talking about.

amiller-gh commented 6 years ago

👍 @add1sun has kicked off the documentation location/format discussion here: https://github.com/nodejs/community-committee/issues/329

Like we talked about at the conf, we don't have any technical plans laid out yet for how to store, ingest, and display docs that live alongside – so this is the perfect time to kick off the conversation!

This shouldn't stop you from writing content though. Feel free to start creating more detailed guides for streams in this repo and we can re-format as needed once the website architecture is fleshed out. If we go the in-repo, multiple-source route, it would be great to have readable-stream as a guinea pig for the new ingestion pipeline 🙂