Home > Blockchain >  Array being doubled after reading a .txt file using fs in nodejs
Array being doubled after reading a .txt file using fs in nodejs

Time:11-24

Problem

Code below is supposed to read a project.skid file and load all of it's lines into an array. For example if project.skid contained "HELLO WORLD", expected output upon executing the script would be simply "HELLO WORLD". Instead, it doubles everything for example: "HELLO WORLD" outputs

HELLO WORLD
HELLO WORLD

Code

const fs = require("fs");

read()

//READING THE INITAL SCRIPT

function read() {

fs.readFile(__dirname   '/project.skid', 'utf8', (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    processfile(data)
  });
};

//SPLITTING INTO LINES

function processfile(data){
    var array = fs.readFileSync('project.skid', 'utf8').split('\n');
    for(i in array) {
        var arrayLength = array.length;
    for (var i = 0; i < arrayLength; i  ) {
    console.log(array[i]);
}
}
} 

CodePudding user response:

You don't need the last part of that for loop - you end up outputting the contents twice.

Instead, you can just clean up your processfile() function like so:

function processfile(data){
  var array = fs.readFileSync('project.skid', 'utf8').split('\n');
  for(i in array) {
    console.log(i)
  } 
}

your first for loop is already iterating through your array - no need to do another for loop based on the array length

  • Related