Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Node.js 入门系列] 逐行读取 readline 模块 #30

Open
webfansplz opened this issue Dec 20, 2019 · 1 comment
Open

[Node.js 入门系列] 逐行读取 readline 模块 #30

webfansplz opened this issue Dec 20, 2019 · 1 comment
Labels

Comments

@webfansplz
Copy link
Owner

webfansplz commented Dec 20, 2019

逐行读取 readline 模块

readline 模块是一个流内容的逐行读取模块,通过 require('readline')引用模块。你可以用 readline 模块来读取 stdin,可以用来逐行读取文件流,也可用它来在控制台和用户进行一些交互。

const readline = require("readline");

const rl = readline.createInterface({
  //  监听的可读流
  input: process.stdin,
  //  逐行读取(Readline)数据要写入的可写流
  output: process.stdout
});

rl.question("你如何看待 null-cli ?", answer => {
  console.log(`感谢您的宝贵意见:${answer}`);
  rl.close();
});

readline

很多有趣的 CLI 工具是基于 readline 造的哦,有兴趣的同学也可以尝试~

上一节: [Node.js 入门系列] 流 stream 模块

下一节: [Node.js 入门系列] 查询字符串 querystring 模块

@Aizener
Copy link

Aizener commented Jan 13, 2022

这节太少了,readline用来读取文件好像也挺好用的:

const rl = readline.createInterface({
  input: fs.createReadStream('./demo.txt')
})
rl.on('line', data => {
  console.log(data)
})
rl.on('close', () => {
  console.log('end')
})

感觉有些时候比createReadStream来设置highWaterMark限制读取大小要方便。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants