共计 1635 个字符,预计需要花费 5 分钟才能阅读完成。
摘要
在实现与用户交互的工具时,总会有类似 c++ 中 cin>> 操作符的功能需求,从命令行读取用户输入然后继续执行。本文简要介绍了在 nodejs 中避免掉使用事件监听的方式,实现同步 和 thenable 风格的代码书写方法。
目录
[隐藏] 在实现与用户交互的工具时,总会有类似 c++ 中 cin>> 操作符的功能需求,从命令行读取用户输入然后继续执行。
在 nodejs 中,避免掉使用事件监听的方式,实现同步的代码书写,可通过如下方法。
1. fs.readSync + process.stdin 同步读取用户输入
使用 fs.readSync 从 process.stdin 中读取。示例:
const fs = require('fs'); | |
function readSyncByfs(tips) { | |
let response; | |
tips = tips || '> '; | |
process.stdout.write(tips); | |
process.stdin.pause(); | |
response = fs.readSync(process.stdin.fd, 1000, 0, 'utf8'); | |
process.stdin.end(); | |
return response[0].trim(); | |
} | |
console.log(readSyncByfs('请输入任意字符:')); |
在 nodejs v6 版本,fs.readSync
会报警告。应当如下方式实现:
const fs = require('fs'); | |
function readSyncByfs(tips) { | |
tips = tips || '> '; | |
process.stdout.write(tips); | |
process.stdin.pause(); | |
const buf = Buffer.allocUnsafe(10000); | |
fs.readSync(process.stdin.fd, buf, 0, 10000, 0); | |
process.stdin.end(); | |
retrun buf.toString('utf8', 0, response).trim(); | |
} |
2. readline.question 获取用户输入
使用 readline 模块。示例:
const readline = require('readline'); | |
function readSyncByRl(tips) { | |
tips = tips || '> '; | |
return new Promise((resolve) => { | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
rl.question(tips, (answer) => { | |
rl.close(); | |
resolve(answer.trim()); | |
}); | |
}); | |
} | |
readSyncByRl('请输入任意字符:').then((res) => { | |
console.log(res); | |
}); |
严格来讲,readline 模块返回的是基于 Promise 的异步回调,当然也可基于 require('child_process').spawnSync
进行简单的同步实现。
3. 基于 nodejs 模块 readline-sync
readline-sync
模块是 readline
模块的同步实现。示例:
var readlineSync = require('readline-sync'); | |
// Wait for user's response. | |
var userName = readlineSync.question('May I have your name? '); | |
console.log('Hi ' + userName + '!'); | |
// Handle the secret text (e.g. password). | |
var favFood = readlineSync.question('What is your favorite food? ', { | |
hideEchoBack: true // The typed text on screen is hidden by `*` (default). | |
}); | |
console.log('Oh, ' + userName + ' loves ' + favFood + '!'); |
详细参考:https://github.com/anseki/readline-sync
如有更多更好的方法实现,欢迎讨论。
正文完