Created
October 7, 2014 21:01
-
-
Save lxe/e9e80f8b467c2def2ebc to your computer and use it in GitHub Desktop.
Nested readables
This file contains hidden or 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
| function readOneLine(callback) { | |
| function readableListener () { | |
| var chunk = process.stdin.read(); | |
| if (!chunk) return; | |
| // Let's disconnect our event when we're ready to call back | |
| process.stdin.removeListener('readable', readableListener); | |
| // Attempt 1: | |
| // Not pausing or ending, will run all 3 readers, but expect | |
| // one more extraneous line | |
| // | |
| // Attempt 2: | |
| // pause() here will not let 'Second' reader run and just exit the process | |
| // process.stdin.pause(); | |
| // Attempt 3: | |
| // Removing the listener, and then checking if any listeners were added | |
| // "later," makes 'Third' fail to run and just exit the process | |
| // setImmediate(function () { | |
| // if (require('events').EventEmitter.listenerCount(process.stdin, 'readable') === 0) { | |
| // process.stdin.pause(); | |
| // }; | |
| // }) | |
| return callback(null, chunk.toString()); | |
| } | |
| process.stdin.on('readable', readableListener); | |
| } | |
| // First | |
| process.stdout.write('First: '); | |
| readOneLine(function (err, data) { | |
| console.log('Got data from First:' + data); | |
| // Second | |
| process.stdout.write('Second: '); | |
| readOneLine(function (err, data) { | |
| console.log('Got data from Second:' + data); | |
| // Third | |
| setTimeout(function () { | |
| process.stdout.write('Third: '); | |
| readOneLine(function (err, data) { | |
| console.log('Got data from Third:' + data); | |
| }); | |
| }, 100); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment