Skip to content

Instantly share code, notes, and snippets.

@dhensen
Created May 23, 2018 14:12
Show Gist options
  • Save dhensen/7f18c901af43c1a1724112f7c34f3a6b to your computer and use it in GitHub Desktop.
Save dhensen/7f18c901af43c1a1724112f7c34f3a6b to your computer and use it in GitHub Desktop.
serially read lines via asynchronous readline interface using semaphore with capacity 1
// 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