index.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. //filter will reemit the data if cb(err,pass) pass is truthy
  2. // reduce is more tricky
  3. // maybe we want to group the reductions or emit progress updates occasionally
  4. // the most basic reduce just emits one 'data' event after it has recieved 'end'
  5. var Stream = require('stream').Stream
  6. , es = exports
  7. , through = require('through')
  8. , from = require('from')
  9. , duplex = require('duplexer')
  10. , map = require('map-stream')
  11. , pause = require('pause-stream')
  12. , split = require('split')
  13. , pipeline = require('stream-combiner')
  14. , immediately = global.setImmediate || process.nextTick;
  15. es.Stream = Stream //re-export Stream from core
  16. es.through = through
  17. es.from = from
  18. es.duplex = duplex
  19. es.map = map
  20. es.pause = pause
  21. es.split = split
  22. es.pipeline = es.connect = es.pipe = pipeline
  23. // merge / concat
  24. //
  25. // combine multiple streams into a single stream.
  26. // will emit end only once
  27. es.concat = //actually this should be called concat
  28. es.merge = function (/*streams...*/) {
  29. var toMerge = [].slice.call(arguments)
  30. if (toMerge.length === 1 && (toMerge[0] instanceof Array)) {
  31. toMerge = toMerge[0] //handle array as arguments object
  32. }
  33. var stream = new Stream()
  34. stream.setMaxListeners(0) // allow adding more than 11 streams
  35. var endCount = 0
  36. stream.writable = stream.readable = true
  37. if (toMerge.length) {
  38. toMerge.forEach(function (e) {
  39. e.pipe(stream, {end: false})
  40. var ended = false
  41. e.on('end', function () {
  42. if(ended) return
  43. ended = true
  44. endCount ++
  45. if(endCount == toMerge.length)
  46. stream.emit('end')
  47. })
  48. })
  49. } else {
  50. process.nextTick(function () {
  51. stream.emit('end')
  52. })
  53. }
  54. stream.write = function (data) {
  55. this.emit('data', data)
  56. }
  57. stream.destroy = function () {
  58. toMerge.forEach(function (e) {
  59. if(e.destroy) e.destroy()
  60. })
  61. }
  62. return stream
  63. }
  64. // writable stream, collects all events into an array
  65. // and calls back when 'end' occurs
  66. // mainly I'm using this to test the other functions
  67. es.writeArray = function (done) {
  68. if ('function' !== typeof done)
  69. throw new Error('function writeArray (done): done must be function')
  70. var a = new Stream ()
  71. , array = [], isDone = false
  72. a.write = function (l) {
  73. array.push(l)
  74. }
  75. a.end = function () {
  76. isDone = true
  77. done(null, array)
  78. }
  79. a.writable = true
  80. a.readable = false
  81. a.destroy = function () {
  82. a.writable = a.readable = false
  83. if(isDone) return
  84. done(new Error('destroyed before end'), array)
  85. }
  86. return a
  87. }
  88. //return a Stream that reads the properties of an object
  89. //respecting pause() and resume()
  90. es.readArray = function (array) {
  91. var stream = new Stream()
  92. , i = 0
  93. , paused = false
  94. , ended = false
  95. stream.readable = true
  96. stream.writable = false
  97. if(!Array.isArray(array))
  98. throw new Error('event-stream.read expects an array')
  99. stream.resume = function () {
  100. if(ended) return
  101. paused = false
  102. var l = array.length
  103. while(i < l && !paused && !ended) {
  104. stream.emit('data', array[i++])
  105. }
  106. if(i == l && !ended)
  107. ended = true, stream.readable = false, stream.emit('end')
  108. }
  109. process.nextTick(stream.resume)
  110. stream.pause = function () {
  111. paused = true
  112. }
  113. stream.destroy = function () {
  114. ended = true
  115. stream.emit('close')
  116. }
  117. return stream
  118. }
  119. //
  120. // readable (asyncFunction)
  121. // return a stream that calls an async function while the stream is not paused.
  122. //
  123. // the function must take: (count, callback) {...
  124. //
  125. es.readable =
  126. function (func, continueOnError) {
  127. var stream = new Stream()
  128. , i = 0
  129. , paused = false
  130. , ended = false
  131. , reading = false
  132. stream.readable = true
  133. stream.writable = false
  134. if('function' !== typeof func)
  135. throw new Error('event-stream.readable expects async function')
  136. stream.on('end', function () { ended = true })
  137. function get (err, data) {
  138. if(err) {
  139. stream.emit('error', err)
  140. if(!continueOnError) stream.emit('end')
  141. } else if (arguments.length > 1)
  142. stream.emit('data', data)
  143. immediately(function () {
  144. if(ended || paused || reading) return
  145. try {
  146. reading = true
  147. func.call(stream, i++, function () {
  148. reading = false
  149. get.apply(null, arguments)
  150. })
  151. } catch (err) {
  152. stream.emit('error', err)
  153. }
  154. })
  155. }
  156. stream.resume = function () {
  157. paused = false
  158. get()
  159. }
  160. process.nextTick(get)
  161. stream.pause = function () {
  162. paused = true
  163. }
  164. stream.destroy = function () {
  165. stream.emit('end')
  166. stream.emit('close')
  167. ended = true
  168. }
  169. return stream
  170. }
  171. //
  172. // map sync
  173. //
  174. es.mapSync = function (sync) {
  175. return es.through(function write(data) {
  176. var mappedData
  177. try {
  178. mappedData = sync(data)
  179. } catch (err) {
  180. return this.emit('error', err)
  181. }
  182. if (mappedData !== undefined)
  183. this.emit('data', mappedData)
  184. })
  185. }
  186. //
  187. // log just print out what is coming through the stream, for debugging
  188. //
  189. es.log = function (name) {
  190. return es.through(function (data) {
  191. var args = [].slice.call(arguments)
  192. if(name) console.error(name, data)
  193. else console.error(data)
  194. this.emit('data', data)
  195. })
  196. }
  197. //
  198. // child -- pipe through a child process
  199. //
  200. es.child = function (child) {
  201. return es.duplex(child.stdin, child.stdout)
  202. }
  203. //
  204. // parse
  205. //
  206. // must be used after es.split() to ensure that each chunk represents a line
  207. // source.pipe(es.split()).pipe(es.parse())
  208. es.parse = function (options) {
  209. var emitError = !!(options ? options.error : false)
  210. return es.through(function (data) {
  211. var obj
  212. try {
  213. if(data) //ignore empty lines
  214. obj = JSON.parse(data.toString())
  215. } catch (err) {
  216. if (emitError)
  217. return this.emit('error', err)
  218. return console.error(err, 'attempting to parse:', data)
  219. }
  220. //ignore lines that where only whitespace.
  221. if(obj !== undefined)
  222. this.emit('data', obj)
  223. })
  224. }
  225. //
  226. // stringify
  227. //
  228. es.stringify = function () {
  229. var Buffer = require('buffer').Buffer
  230. return es.mapSync(function (e){
  231. return JSON.stringify(Buffer.isBuffer(e) ? e.toString() : e) + '\n'
  232. })
  233. }
  234. //
  235. // replace a string within a stream.
  236. //
  237. // warn: just concatenates the string and then does str.split().join().
  238. // probably not optimal.
  239. // for smallish responses, who cares?
  240. // I need this for shadow-npm so it's only relatively small json files.
  241. es.replace = function (from, to) {
  242. return es.pipeline(es.split(from), es.join(to))
  243. }
  244. //
  245. // join chunks with a joiner. just like Array#join
  246. // also accepts a callback that is passed the chunks appended together
  247. // this is still supported for legacy reasons.
  248. //
  249. es.join = function (str) {
  250. //legacy api
  251. if('function' === typeof str)
  252. return es.wait(str)
  253. var first = true
  254. return es.through(function (data) {
  255. if(!first)
  256. this.emit('data', str)
  257. first = false
  258. this.emit('data', data)
  259. return true
  260. })
  261. }
  262. //
  263. // wait. callback when 'end' is emitted, with all chunks appended as string.
  264. //
  265. es.wait = function (callback) {
  266. var arr = []
  267. return es.through(function (data) { arr.push(data) },
  268. function () {
  269. var body = Buffer.isBuffer(arr[0]) ? Buffer.concat(arr)
  270. : arr.join('')
  271. this.emit('data', body)
  272. this.emit('end')
  273. if(callback) callback(null, body)
  274. })
  275. }
  276. es.pipeable = function () {
  277. throw new Error('[EVENT-STREAM] es.pipeable is deprecated')
  278. }