Node.js readline 的常用API

282 阅读1分钟

这里我来总结一下Node.js readline 模块的常用API

创建接口

readline.createInterface() 创建一个 readline 接口实例:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

提问用户输入

rl.question() 可用于提示用户输入内容:

rl.question('What do you think of Node.js? ', (answer) => {
  console.log(`Thank you for your valuable feedback: ${answer}`);
});

读取每一行

rl.on('line', () => {}) 可以读取每一行的输入:

rl.on('line', (line) => {
  console.log(`Received: ${line}`);
});

关闭接口

rl.close() 关闭接口并结束输入:

rl.close();

光标移动

rl.moveCursor() 移动光标位置

rl.cursorTo() 移动到指定位置

清除内容

rl.clearScreen() 清除屏幕

rl.clearLine() 清除当前行

rl.moveCursor(process.stdout,0,0);

其他方法

rl.pause() 暂停readline rl.resume() 恢复readline rl.write() 输出内容 等等

以上就是 Node.js readline 模块的主要API,把常用方法和示例讲解了一遍,希望能对大家学习和应用 readline 提供参考。