粥里有勺糖

vuePress-theme-reco 粥里有勺糖    2018 - 2023
粥里有勺糖 粥里有勺糖

Choose mode

  • dark
  • auto
  • light
关于我
备战春秋
  • 心得总结
  • 校招考点汇总
  • 面经汇总
  • 复习自查
技术笔记
  • 技术教程
  • 模板工程
  • 源码学习
  • 技术概念
  • 个人作品
  • 学习笔记
计算机基础
  • 算法与数据结构
  • 操作系统
  • 计算机网络
  • 设计模式
  • 剑指offer
大前端
  • javascript
  • vue
  • html
  • css
  • 🌏浏览器专题
  • Web性能优化
  • regexp
  • node
面试
  • 问解
  • javascript
  • css
  • 手撕代码
  • 性能优化
  • 综合问题
  • 面经汇总
  • 小程序
手撕代码
  • 数据结构与算法
  • javascript
  • css
个人站点
  • GitHub (opens new window)
  • 博客园 (opens new window)
  • 掘金 (opens new window)
线上作品
  • 轻取(文件收集) (opens new window)
  • 个人图床 (opens new window)
  • 考勤小程序 (opens new window)
  • 时光恋人 (opens new window)
  • 在线简历生成 (opens new window)
留言板
Github (opens new window)
author-avatar

粥里有勺糖

285

文章

40

标签

关于我
备战春秋
  • 心得总结
  • 校招考点汇总
  • 面经汇总
  • 复习自查
技术笔记
  • 技术教程
  • 模板工程
  • 源码学习
  • 技术概念
  • 个人作品
  • 学习笔记
计算机基础
  • 算法与数据结构
  • 操作系统
  • 计算机网络
  • 设计模式
  • 剑指offer
大前端
  • javascript
  • vue
  • html
  • css
  • 🌏浏览器专题
  • Web性能优化
  • regexp
  • node
面试
  • 问解
  • javascript
  • css
  • 手撕代码
  • 性能优化
  • 综合问题
  • 面经汇总
  • 小程序
手撕代码
  • 数据结构与算法
  • javascript
  • css
个人站点
  • GitHub (opens new window)
  • 博客园 (opens new window)
  • 掘金 (opens new window)
线上作品
  • 轻取(文件收集) (opens new window)
  • 个人图床 (opens new window)
  • 考勤小程序 (opens new window)
  • 时光恋人 (opens new window)
  • 在线简历生成 (opens new window)
留言板
Github (opens new window)
  • Node

    • NodeJS
    • Node侧实现内容压缩(gzip/br/deflate)介绍与实践
    • 使用TS封装操作MongoDB数据库的工具方法
    • 使用Node.js从终端读入内容
    • 实现一个幽灵依赖扫描工具

使用Node.js从终端读入内容

vuePress-theme-reco 粥里有勺糖    2018 - 2023

使用Node.js从终端读入内容

粥里有勺糖 2021-06-17 大前端node.js

# 使用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

代码逻辑为:

  • 输入两个数字
  • 计算这两数字的和

假设上面的文件叫index.js,接下来我们直接输入下面运行

node index.js
1

运行结果如下:

图片

感觉并没有其它语言用起来那么安逸,比如:

  • C++:cin>>param
  • C:scanf("%s",&param)
  • 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

我们在编写一个新的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
node test.js
1

运行结果

图片

现在用起来就方便多了,已经有一点其它语言的味道了

# 其它工具方法封装

util.js

# print

不自动换行的打印方法

function print(str){
    process.stdout.write(str)
}
1
2
3

使用:

print('hello world\n')
print('666\n')
1
2

# readNumber

读取一个数字,因为readline读取的所有内容都是字符串的形式,读取数字的话需要自己做转换

const readline = require('./readline')

async function readNumber(){
    return +(await readline())
}
1
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

运行结果

图片

# 方法汇总

咱可以创建一个 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

# 资料汇总

  • readline模块:逐行读取 (opens new window)
  • demo源码 (opens new window)
Edit this page (opens new window)
Last Updated: 2022/5/15 12:46:34