fork download
  1. 'use strict'
  2.  
  3. var stream = require('stream')
  4. var stdin = process.stdin
  5. var stdout = process.stdout
  6.  
  7.  
  8. // 本実装
  9. stream.prototype.addLineSwitch = function (outputs, controller) {
  10. var input = this
  11. var output_trash = new stream.Writable()
  12. output_trash._write = function () {}
  13. var rl = require('readline').createInterface(input, output_trash)
  14. rl.on('line', function (line) {
  15. var output = outputs[controller(line, outputs)]
  16. if (output) output.write(new Buffer(line + '\n'))
  17. })
  18. }
  19.  
  20.  
  21. // ObjectStream
  22. function ObjectStream() {
  23. var obj_stream = new stream.Duplex({objectMode: true})
  24. obj_stream.data_array = []
  25. obj_stream._write = function (data, _, callback) {
  26. this.data_array.push(data)
  27. callback()
  28. }
  29. obj_stream._read = function (size) {
  30. this.push(this.data_array.shift() || null)
  31. }
  32. return obj_stream
  33. }
  34.  
  35.  
  36. //
  37. var even = new ObjectStream
  38. var odd = new ObjectStream
  39.  
  40.  
  41. // 出力先とコントローラーの設定
  42. var outputs = [even, odd]
  43. var controller = function (line, outputs) {
  44. return line % 2
  45. }
  46.  
  47.  
  48. // 標準入力にスイッチリスナを追加
  49. stdin.addLineSwitch(outputs, controller)
  50.  
  51.  
  52.  
  53.  
  54. ###以下どこかのタイミングで###
  55.  
  56. for (var i of even.data_array) console.log(i) //等
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty