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

Jun 02, 2018 am 11:49 AM
javascript node.js readline

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

// 输入 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

1

2

3

4

5

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

1

2

3

4

5

/*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)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles