简体   繁体   中英

node.js:readLine but last line doesn't save in array

Use: Node.js 8.x

Purpose: Reading standard input and storing it in an array

Error: the Last Line doesn't save in array.

what is my misunderstanding about javascript? async and sync?

const promise = require('promise')
,   readline = require('readline');

const stdRl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

GLOBAL_COUNTER_READLINE = 0;
GLOBAL_MAPSIZE = 0;
GLOBAL_MAPDATA = [];

stdRl.on('line', (input) => {

  // first line : setMapSize
  // second line ~ GLOBAL_MAPSIZE : appendMapDataRow
  // GLOBAL_MAPSIZE + 1 line : getMapData, countChar
  if (GLOBAL_COUNTER_READLINE == 0) {

    // setMapSize;
    GLOBAL_MAPSIZE = input;

    console.log(`Map Size is : ${GLOBAL_MAPSIZE}`);

  } else if (GLOBAL_COUNTER_READLINE != GLOBAL_MAPSIZE) {

    // appendMapDataRow
    GLOBAL_MAPDATA.push(input);

  } else if(GLOBAL_COUNTER_READLINE == GLOBAL_MAPSIZE){

    //getMapData
    for (var row = 0; row < GLOBAL_MAPDATA.length; row++) {
      console.log(`${GLOBAL_MAPDATA[row]}`);
    }

    stdRl.close();
  }
  GLOBAL_COUNTER_READLINE++;
});

javascript is awesome, but it's hard to me.

Your main issue is that, since the number of lines is the first value you read, you shouldn't actually increment the counter for it. You should start incrementing once you actually receive the first line of data.

if (GLOBAL_MAPSIZE == 0) {

  GLOBAL_MAPSIZE = input;
  console.log(`Map Size is : ${GLOBAL_MAPSIZE}`);

} else if (GLOBAL_COUNTER_READLINE < GLOBAL_MAPSIZE) {

  GLOBAL_MAPDATA.push(input);
  GLOBAL_COUNTER_READLINE++; // <-- move the increment here

} else {

  for (var row = 0; row < GLOBAL_MAPDATA.length; row++) {
    console.log(`${GLOBAL_MAPDATA[row]}`);
  }

  stdRl.close();
}

Another potential future issue is that you're instantiating objects but using them as primitive values.

Two instances of Number are never equal:

 console.log( new Number(0) == new Number(0) // false ) 

Because objects are compared by referential equality (basically checking if they are the same instance; if they refer to the same object in memory).

You could compare their values:

 console.log( new Number(0).valueOf() == new Number(0).valueOf() // true ) 

But it's much simpler to just use the raw primitive.

 console.log( 0 == 0 // true ) 

So in your code:

GLOBAL_COUNTER_READLINE = 0;
GLOBAL_MAPSIZE = 0;
GLOBAL_MAPDATA = [];

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