首页 > 语言 > JavaScript > 正文

Node.js readline模块与util模块的使用

2024-05-06 15:21:15
字体:
来源:转载
供稿:网友

1. 使用readline模块逐行读取流数据

1.1. 创建Interface对象

在readline模块中,通过Interface对象的使用来实现逐行读取流数据的处理。因此首先要创建Interface对象,在readline模块中,可以通过createInterface方法来创建Interface对象.readline.createInterface(options),options为一个对象,属性如下

    input: 属性值为一个可用来读取流数据的对象,用于指定读入数据的来源。 output: 属性值为一个可用来写入流数据的对象,用于指定数据的输出目标。 computer: 属性值为一个函数,用于指定Tab补全处理。函数的参数值被自动设定为从该行中读入的Tab字符之前的数据,该函数应该返回一个由所有用于Tab补全时的匹配字符串组成的数组以及从该行中读入的Tab字符之前的数据。 terminal: 该属性为一个布尔类型的属性,当需要像一个终端那样实时地将输入数据流进行输出,且需要在输出数据中写入ANSI/VT100控制字符串时,需要将该属性值设置为true,默认属性值等于output属性值对象的isTTY属性值。
// 输入 exit, quit,q这三个任意之一的时候,会退出const readline = require('readline');let rl = readline.createInterface({  input: process.stdin,  output: process.stdout,  completer: completer});rl.on('line', (line) => {  if (line === 'exit' || line === 'quit' || line === 'q') {    rl.close();  } else {    console.log('您输入了:', line);  }});rl.on('close', () => {  console.log('行数据读取操作被终止');});function completer(line) {  const completions = '.help .error .exit .quit .q'.split(' ');  let hits = completions.filter((c) => {    return c.indexOf(line) === 0;  });  return [hits.length ? hits : completions, line]}

1.2. 使用Interface对象逐行读取文件

原fs.js文件的内容

console.log('this is line 1');console.log('this is line 2');console.log('this is line 3');console.log('this is line 4');console.log('this is line 5');

代码内容

const readline = require('readline');const fs = require('fs');let file = fs.createReadStream('./fs.js');let out = fs.createWriteStream('./anotherFs.js');let index = 1;out.write('/*line' + index.toString() + ": */");let rl = readline.createInterface({  input: file,  output: out,  terminal: true});rl.on('line', (line) => {  if (line === '') {    rl.close();  } else {    index++;    out.write('/*line' + index.toString() + ': */');  }});

生成的anotherFs.js文件的内容

/*line1: */console.log('this is line 1');/*line2: */console.log('this is line 2');/*line3: */console.log('this is line 3');/*line4: */console.log('this is line 4');/*line5: */console.log('this is line 5');/*line6: */

2. 使用util模块中提供的一些方法

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选