Created
May 23, 2018 14:12
-
-
Save dhensen/7f18c901af43c1a1724112f7c34f3a6b to your computer and use it in GitHub Desktop.
serially read lines via asynchronous readline interface using semaphore with capacity 1
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
// create a file named input containing 1, 2, 3, 4 on separate lines | |
// cat input | node serial-readline.js | |
// output (shows bot stdin and stdout): | |
// 1 | |
// start handler | |
// end handler | |
// 2 | |
// 3 | |
// 4processing: 1 | |
// start handler | |
// end handler | |
// processing: 2 | |
// start handler | |
// end handler | |
// processing: 3 | |
// start handler | |
// end handler | |
// processing: 4 | |
const readline = require('readline'); | |
var sem = require('semaphore')(1); | |
const someThingAsync = async data => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log('processing: ' + data); | |
resolve(data); | |
sem.leave(); | |
}, Math.random() * 500); | |
}); | |
}; | |
const handler = data => { | |
sem.take(function () { | |
// notice that this function is NOT async | |
console.log('start handler'); | |
someThingAsync(data); | |
console.log('end handler'); | |
}); | |
}; | |
function run() { | |
this.io = readline.createInterface(process.stdin, process.stdout); | |
this.io.on('line', handler); | |
} | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment