简体   繁体   中英

Can someone help me with this syntax?

This maybe silly but I'm unfamiliar with the syntax here:

var stdin = '';
process.stdin.on('data', function (chunk) {
  stdin += chunk;
}).on('end', function() {
  var lines = stdin.split('\n');
  for(var i=0; i<lines.length; i++) {
    process.stdout.write(lines[i]);
  }
});

I'm supposed to write a program that squares a number, which I know how to do, but I've never encountered this type of structure. I understand the loop and that process.stdout.write is essentially console.log The test cases inputs are 5 and 25. Outputs should be 25 and 625.

Where am I supposed to write the code to do this?

You can put it in a file sample.js and run it:

node sample.js

This process.stdin refers to the stdin stream (incoming data from other applications, for example, a shell input , so basically this:

process.stdin.on('data', function (chunk) {
  stdin += chunk;
})

says, whenever there new data (user typed in something into a console, hosting application send some data), read it and store it in stdin variable. Then, when the stdin stream is over (for example, a user finished entering data):

.on('end', function() {
  var lines = stdin.split('\n');
  for(var i=0; i<lines.length; i++) {
    process.stdout.write(lines[i]);
  }
})

the code outputs back what a user typed in.

It appears all of the infrastructure is there. All that's left is actually squaring your numbers.

process.stdin and process.stdout are node streams which are asynchronous and so use events to tell you what's going on with them. data is the event for when there is data ready to process and end is for when there's no more data. The code just snarfs process.stdin and then, once the data is all in memory, processes it.

The end anonymous function would probably be best implemented like this:

function() {
  stdin.split('\n').foreach(function(line){
     var value = line.trim()|0;
     process.stdout.write(value * value);
  });
}

Off topic: The memory footprint might be improved by processing the stream as it comes in rather than collecting it and then processing it all at once. This depends on the sizes of the input and the input buffer:

var buffer = '';
var outputSquare = function(line) {
  var value = line.trim()|0;
  process.stdout.write(value * value);
};
process.stdin.on('data', function (chunk) {
  var lines = (buffer + chunk).split('\n');
  buffer = lines.pop();
  lines.foreach(outputSquare);
}).on('end', function() {
  outputSquare(buffer);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM