Node.js进修之路20——readline模块与util模块

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模块中供应的一些要领

+format要领
类似于C语言中的printf要领,将第一个参数值作为一个花样化字符串,将其他参数值作为该花样化字符串中所运用的各中参数,返回一个经由花样化处置惩罚后的字符串.util.format('您输入了%d个参数,参数值分别为%s,%s,%s',3,'nice','excelent','holy');
花样化字符串中,能够运用的参数指定标记

*`%s`:用于指定字符串参数
*`%d`:用于指定数值参数,包括整数及浮点数
*`%j`:用于指定一个`JSON`对象
*`%%`:用于指定一个百分号
*假如花样化字符串中运用的参数个数多于format要领中运用的除了`format`参数以外的其他参数,则花样化字符串中多于的参数将不被替代.`console.log(util.format('%s:%s','one'));`
*假如花样化字符串中运用的参数个数少于`format`要领中运用的除了`format`参数以外的其他参数,则依据`format`要领中多于参数值的范例自动将其转换为字符串,中心运用一个空格举行支解.

+inspect(object,[options])返回一个字符串,该字符串包括了对象的信息,在调试应用程序的过程当中异常有效.

*`showHidden<boolean>`假如为`true`,则`object`的不可枚举的标记与属性也会被包括在花样化后的效果中.默许为`false.`
*`depth<number>`指定花样化`object`时递归的次数.这对检察大型庞杂对象很有效.默许为`2`.若要无穷地递归则传入`null`.
*`colors<boolean>`假如为`true`,则输出款式运用`ANSI`色彩代码.默许为`false`.色彩可自定义.
*`customInspect<boolean>`假如为`false`,则`object`上自定义的`inspect(depth,opts)`函数不会被挪用.默许为`true`.
*`showProxy<boolean>`假如为`true`,则`Proxy`对象的对象和函数会展现它们的`target`和`handler`对象.默许为`false`.
*`maxArrayLength<number>`指定花样化时数组和`TypedArray`元素能包括的最大数目.默许为`100`.设为`null`则显式悉数数组元素.设为`0*`或负数则不显式数组元素.
*`breakLength<number>`一个对象的键被拆分红多行的长度.设为`Infinity`则花样化一个对象为单行.默许为`60`.

+自定义util.inspect色彩
能够经由过程util.inspect.stylesutil.inspect.colors属性全局地自定义util.inspect的色彩输出(假如已启用)

const util = require('util');
console.log(util.format('您输入了%d个参数,参数值分别为%s,%s,%s', 3, 'nice', 'excelent', 'holy'));
//您输入了3个参数,参数值分别为nice,excelent,holy
console.log(util.format('一个JSON对象%j', {'name': 'jack', 'age': 25}));
// 一个JSON对象{"name":"jack","age":25}
console.log(util.format('一个百分号%'));// 一个百分号%
console.log(util.format('%s:%s', 'one'));// one:%s
console.log(util.format('%s', 'one', 'two', 'three', {'name': 'jack'}));

function test(one, two) {
    return one + two;
}

let parent = new Object();
parent.name = 'parent';
parent.func = test;

let child1 = new Object();
child1.name = 'child1';
parent.child1 = child1;

let child2 = new Object();
child2.name = 'child2';
child1.child = child2;

let child3 = new Object();
child3.name = 'child3';
child2.child = child3;

child2.inspect = function (depth) {
    return util.inspect(this, {depth: depth - 2, customInspect: false})
};
console.log(util.inspect(parent, {customInspect: true, depth: 4}));
/**
 * { name: 'parent',
 *   func: [Function: test],
 *   child1:
 *    { name: 'child1',
 *      child: { name: 'child2', child: [Object], inspect: [Function] } } }
 * **/
    原文作者:Karuru
    原文地址: https://segmentfault.com/a/1190000013449214
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞