Node readline 简单实现
function myReadline(callback) {
const input = process.stdin;
const output = process.stdout;
let line = ''
function handleKeyPress(s){
line += s
output.write(s)
switch (s) {
case '\r':
callback(line)
input.pause()
break;
}
}
input.on('keyPress', handleKeyPress)
emitKeyPressEvent(input)
input.setRawMode(true)
input.resume()
}
function emitKeyPressEvent(stream) {
function onData(chunk) {
kp.next(chunk.toString())
}
let kp = keyPress(stream)
kp.next()
stream.on('data', onData)
}
function* keyPress(stream) {
while(true) {
const s = yield
stream.emit('keyPress', s)
}
}
myReadline((input) => {
console.log('log: ' + input)
})