How does the Process module obtain the input data of the terminal?

The two-way communication between the client and the server is realized through code, because we cannot input information directly on the terminal, such as inputting information on the client terminal and sending it to the server, such functions need 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 a method for obtaining terminal input data, which will be described in detail below.

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

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 the [Enter] key needs to be pressed after inputting a message, the system will recognize this action as a space, so use trim0 to remove this space.

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

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

Open the terminal and execute demo6-6.is, the result is shown in the figure.
1671615926485_demo6.jpg

demo6-6js execution results

A blinking cursor appears on the second line in the figure, and you can enter the content in the terminal at this time, for example, enter "123456" and press the [Enter] key, as shown below.

1671615919910_command prompt, .jpg

Figure to get terminal input

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

Guess you like

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