Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
}
}
} 

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading