Home > Web Front-end > JS Tutorial > How to use readline module and util module in Node.js

How to use readline module and util module in Node.js

亚连
Release: 2018-06-02 11:49:39
Original
1490 people have browsed it

This article mainly introduces the use of Node.js readline module and util module. Now I share it with you and give you a reference.

1. Use the readline module to read stream data line by line

1.1. Create an Interface object

In the readline module, through the use of the Interface object To realize the processing of reading stream data line by line. Therefore, you must first create an Interface object. In the readline module, you can create an Interface object through the createInterface method. readline.createInterface(options), options is an object, and the attributes are as follows

  1. input: Attributes The value is an object that can be used to read stream data, used to specify the source of the read data.

  2. output: The attribute value is an object that can be used to write stream data and is used to specify the output destination of the data.

  3. computer: The attribute value is a function used to specify Tab completion processing. The parameter value of the function is automatically set to the data before the Tab character read from the line. The function should return an array consisting of all matching strings used for Tab completion and the data read from the line. The data before the Tab character.

  4. terminal: This attribute is a Boolean type attribute. When it is necessary to output the input data stream in real time like a terminal, and ANSI/VT100 control needs to be written in the output data When it is a string, the attribute value needs to be set to true. The default attribute value is equal to the isTTY attribute value of the output attribute value object.

// 输入 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]
}
Copy after login

1.2. Use the Interface object to read the file line by line

The content of the original fs.js file

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');
Copy after login

Code content

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() + ': */');
  }
});
Copy after login

Contents of the generated anotherFs.js file

/*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: */
Copy after login

2. Use some methods provided in the util module

format method

is similar to the printf method in C language, Use the first parameter value as a format string, use the other parameter values ​​as each parameter used in the format string, and return a formatted string.util.format('You entered %d parameters, the parameter values ​​are %s, %s, %s', 3, 'nice', 'excelent', 'holy');
Parameter specification symbols that can be used in the format string

  1. *`%s`: used to specify string parameters

  2. *`%d`: used to specify numerical parameters, including integers and Floating point number

  3. *`%j`: used to specify a `JSON` object

  4. *`%%`: used to specify a Percent sign

  5. *If the number of parameters used in the format string is more than the other parameters used in the format method except the `format` parameter, the format string Parameters that are more than will not be replaced.`console.log(util.format('%s:%s','one'));`

  6. *If formatted If the number of parameters used in the string is less than the other parameters used in the `format` method except the `format` parameter, it will be automatically converted into a string according to the type of the parameter value in the `format` method. Use a space to separate.

inspect(object,[options]) returns a string that contains information about the object, which is very useful in debugging applications.

  1. *`showHidden`If `true`, the non-enumerable symbols and properties of `object` will also be included in the formatted result. Default Specifies the number of times to recurse when formatting `object` for `false.`

  2. *`depth`. This is useful for viewing large complex objects. Defaults to `2`. To recurse infinitely, pass in `null`.

  3. *`colors`If `true`, the output style uses `ANSI` color code. The default is` false`. The color can be customized.

  4. *`customInspect`If it is `false`, then the custom `inspect(depth,opts)` function on `object` Will not be called. Defaults to `true`.

  5. *`showProxy`If `true`, the objects and functions of the `Proxy` object will display their` target` and `handler` objects. The default is `false`.

  6. *`maxArrayLength` specifies the maximum number of elements that arrays and `TypedArray` can contain when formatting. Default is `100`. Set to `null` to display all array elements. Set to `0*` or a negative number to not display array elements.

  7. *`breakLength `The keys of an object are split into multiple line lengths. Set to `Infinity` to format an object into a single line. The default is `60`.

Custom util.inspect Color

You can globally customize the color output of util.inspect through the util.inspect.styles and util.inspect.colors properties (if enabled)

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] } } }
 * **/
Copy after login

The above is what I compiled for everyone , I hope it will be helpful to everyone in the future.

Related articles:

Usage of vue carousel plug-in vue-concise-slider

Instances of executing functions after leaving the vue page

Solve the problem of vue page refresh or loss of back parameters

The above is the detailed content of How to use readline module and util module in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template