Inscription:
I have been learning Node.js for the past few days, and I just learned about Node's process object and some of the content in this object. Next, today I will talk about how to use the native process to achieve, basic loop input!
text:
First of all, we have to first understand the process object, what is the process object? The process object actually represents the application of Node.js and is also a global object. I won't go into details again. Today we mainly look at the two special attributes stdin and stdout of the process object.
- stdin: The attribute value is an object that can be used to write to the standard input stream. By default, the standard input stream is in a paused state and needs to be used
process.stdin.resume();
- stdout: The property value is an object that can be used to write to the standard output stream
Knowing the basics, we can take a look at how the code implements the loop input of the process
process.stdin.setEncoding('utf8'); process.stdin.on('readable', function(){ var chunk = process.stdin.read(); // Get the input information if(typeof chunk === 'string'){ chunk = chunk.slice(0,-2); // This is to use slices to cut our carriage return\n process.stdout.write('stringLength:'+ chunk.length +'\n'); } if(chunk === ''){ process.stdin.emit('end'); // trigger end event return } if (chunk !== null) { process.stdout.write('data: '+ chunk +'\n'); } }); process.stdin.on('end', function() { process.stdout.write('end'); });
As you can see, when I input a string, I can get the length of my string, and output the length and string,
And I only type carriage return when I use
slice(0,-2)
The \n is cut out to achieve the effect of filtering carriage return.
Among them, it is worth noting how to trigger the end event of process.stdin !
use
process.stdin.exit()
does not trigger the end event, and we can only use
process.stdin.emit('end');
To trigger, it is worth our attention! It is also helpful for our students who want to use node to brush questions!