Last active
May 26, 2018 18:25
-
-
Save briancavalier/f26f95d5cff9ff4fda249822eb1282ae to your computer and use it in GitHub Desktop.
Convert node async functions into most.js streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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