# 使用Node.js从终端读入内容
# 前言
平时在写练习算法题的时,遇到线上笔试时,大部分在线练题网站都需要自己写输入输出,如常见的牛客
,赛码网
。部分不熟悉Node.js输入输出的朋友,就会感到有力无处使
通常此类网站是会直接提供一个readline
或者read_line
方法用来实现数据录入
实际上Node
也是提供了一个模块readline:逐行读取 (opens new window)来实现此功能的
笔者用过的练题网站只有leetcode (opens new window)在使用js书写时只需要实现功能函数就行,就不需要考虑如何从键盘录入内容
本文就和大家分享一下利用Node-readline模块实现通过终端中录入内容
# 简单使用
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
// 不换行输出
process.stdout.write('请输入两个数字:')
// 监听键入回车事件
rl.on('line', (str) => {
// str即为输入的内容
const [a, b] = str.split(' ')
console.log('和为:', (+a) + (+b));
// 关闭逐行读取流 会触发关闭事件
rl.close()
})
// 监听关闭事件
rl.on('close', () => {
console.log('触发了关闭事件');
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
代码逻辑为:
- 输入两个数字
- 计算这两数字的和
假设上面的文件叫index.js
,接下来我们直接输入下面运行
node index.js
1
运行结果如下:
感觉并没有其它语言用起来那么安逸,比如:
- C++:
cin>>param
- C:
scanf("%s",¶m)
- C#:
param = Console.ReadLine()
- ...等等
怎样才能让Node.js从终端中录入数据变得像上述语言一样简单呢?
我们用动动自己的手指封装一下
# 封装
const rdl = require('readline')
/**
* 读入一行
*/
function readline() {
const rl = rdl.createInterface({
input: process.stdin,
output: process.stdout
})
return new Promise(resolve => {
rl.on('line', (str) => {
resolve(str)
rl.close()
})
})
}
module.exports = readline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
我们在编写一个新的test.js
,上面的叫read.js
放在同一目录下
const readline = require('./readline')
async function main(){
process.stdout.write('第一个单词:')
const a = await readline()
process.stdout.write('第二个单词:')
const b = await readline()
console.log(a , b);
}
main()
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
node test.js
1
运行结果
现在用起来就方便多了,已经有一点其它语言的味道了
# 其它工具方法封装
util.js
不自动换行的打印方法
function print(str){
process.stdout.write(str)
}
1
2
3
2
3
使用:
print('hello world\n')
print('666\n')
1
2
2
# readNumber
读取一个数字,因为readline
读取的所有内容都是字符串的形式,读取数字的话需要自己做转换
const readline = require('./readline')
async function readNumber(){
return +(await readline())
}
1
2
3
4
5
2
3
4
5
测试:
async function main(){
const a = await readline()
const b = await readNumber()
console.log('a',typeof a);
console.log('b',typeof b);
}
main()
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
运行结果
# 方法汇总
咱可以创建一个 index.js文件,然后将readline
,readNumber
,print
三个方法统一对外导出:最终如下
const rdl = require('readline')
function print(str){
process.stdout.write(str)
}
/**
* 读入一行
*/
function readline() {
const rl = rdl.createInterface({
input: process.stdin,
output: process.stdout
})
return new Promise(resolve => {
rl.on('line', (str) => {
resolve(str)
rl.close()
})
})
}
async function readNumber(){
return +(await readline())
}
module.exports = {
print,
readline,
readNumber
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33