Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Last active May 26, 2018 18:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briancavalier/f26f95d5cff9ff4fda249822eb1282ae to your computer and use it in GitHub Desktop.
Save briancavalier/f26f95d5cff9ff4fda249822eb1282ae to your computer and use it in GitHub Desktop.
Convert node async functions into most.js streams
import { readFile } from 'fs'
// Create a stream-returning version of fs.readFile
const readFileS = fromNode(readFile)
// Use it to create a stream containing the files contents
// map(String) to convert Buffer to string
const s = readFileS('./a/file.txt').map(String)
// Observe the contents
s.observe(x => console.log('Stream', x))
import { Stream } from 'most'
// Take a node async function like fs.readFile, and give back
// a Stream-returning function
const fromNode = f =>
function (...args) {
return new Stream(new NodeCallback(f, this, args))
}
// Make a node callback (i.e. function(e, value)) that
// will emit its outcome into a Sink
const nodeCallback = (sink, scheduler) =>
function (e, ...args) {
if(e != null) {
return sink.error(scheduler.now(), e)
}
sink.event(scheduler.now(), args.length < 2 ? args[0] : args)
sink.end(scheduler.now(), undefined)
}
// Source for node async functions
class NodeCallback {
constructor (f, context, args) {
this.f = f
this.context = context
this.args = args
}
run (sink, scheduler) {
this.f.call(this.context, ...this.args, nodeCallback(sink, scheduler))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment