1

How to read two .txt files and turn these 2 files to a 2d array?

I already have a code like this :

var fs = require('fs')
file = './text1.txt'
fs.readFile(file,'utf-8', (e,d) => {
  textByLine = d.split('\r\n');
  console.log("test : " + textByLine[1])
})

source

I succeeded to store the file in a 1d array but now I have 2 files and I want to store them in a 2d array. How to do this?

Thank you

Raphael Deiana
  • 750
  • 4
  • 20
SADmiral
  • 41
  • 4

1 Answers1

1

You can have a variable at top with an empty array, after you read the files and push that result to that variable , like this:

const 2dArray = [];
const fillArray = (path)=> {
  fs.readFile(path,'utf-8', (e,d) => {
    2dArray.push(d.split('\r\n')) // the result is already an array.
  });
});

after that you can call each file like this :

// read the files and push the result to the variable 2dArray
fillArray('./text1.txt'); 
fillArray('./text2.txt');

//you can read the 1st result of your 1st file array like this
const firstPartOfArray = 2dArray[0][0];  // text1 first result value

if you don't need to have the result files in order i strongly recommend to use async function.

also you can use thinks like fs-jetpack package to handle this, or glob

balumanzano
  • 178
  • 8