How does the Process module perform data input in the terminal?

The two-way communication between the client and the server is implemented through code, because we cannot input information directly on the terminal. For example, input information on the client terminal and send it to the server. Such a function needs to rely on the Process module to complete. For each terminal, it is just an interface between standard input and standard output. The Process module provides methods for obtaining terminal input data, which are introduced in detail below.

The Process module is a global object that can be accessed from a Nodejs application without using require0. In Node.js, the data input in the process can be obtained in the following ways, that is, the input data from the terminal.

process.stdin.on('data',function (data) {
    
    
  console.log(data.toString().trim());
});

In the above code, by listening to the data event of the process.stdin object, the data input by the terminal is obtained from the callback function of the data event. Since you need to press the [Enter] key after entering the message, the system will recognize this action as a space, so use trim0 to remove this space.

The following uses a case to demonstrate input in the terminal. Create demo6-6.js in the chapter06 directory, and add the following code to the file.

/**
 *测试获取终端输入
 */
// 通过下面的方式就可以获取用户的输入
process.stdin.on('data',function (data){
    
    
  console.log(data.toString().trim());
});

Open the terminal and execute demo6-6.is. The result is as shown in the figure.

1671615926485_demo6.jpg

demo6-6js execution results

A flashing cursor appears in the second line of the picture. At this time, you can enter content in the terminal. For example, enter "123456" and press the [Enter] key, as shown below.

1671615919910_command prompt,.jpg

Figure gets terminal input

In the picture above, the first "123456" is entered using the keyboard, and the second "123456" is the input information obtained after pressing the [Enter] key and is output to the terminal.

Guess you like

Origin blog.csdn.net/cz_00001/article/details/133037175