Skip to content

Instantly share code, notes, and snippets.

@kirillrogovoy
Created September 10, 2017 07:34
Show Gist options
  • Save kirillrogovoy/d4ede2dca951e3c1d3e32dea13a1fc10 to your computer and use it in GitHub Desktop.
Save kirillrogovoy/d4ede2dca951e3c1d3e32dea13a1fc10 to your computer and use it in GitHub Desktop.
An example of using object steams in Node
const fetch = require('node-fetch')
const { Transform, PassThrough } = require('stream')
// giving the starting point a meaningful name
const processRates = new PassThrough({
writableObjectMode: true,
readableObjectMode: true
})
const promiseResolve = new Transform({
writableObjectMode: true,
readableObjectMode: true,
transform (promise, encoding, callback) {
promise.then(x => callback(null, x)).catch(callback)
}
})
const gbpRate = new Transform({
writableObjectMode: true,
readableObjectMode: true,
transform (json, encoding, callback) {
callback(null, json.rates.GBP)
}
})
const format = new Transform({
writableObjectMode: true,
transform (rate, encoding, callback) {
callback(null, rate.toString() + '\n')
}
})
processRates
.pipe(promiseResolve)
.pipe(gbpRate)
.pipe(format)
.pipe(process.stdout)
for (let i = 1; i < 10; i++) {
fetch(`http://api.fixer.io/2000-01-0${i}`)
.then(processRates.write.bind(processRates))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment