Home > Net >  I am trying to take two different files and sum the data
I am trying to take two different files and sum the data

Time:05-29

So I wrote this fs function to read files data from a file:

const fs = require("fs");

const read = function (file) {
  fs.readFile(file, "utf8", (err, data) => {
    if (err !== null) {
      throw err;
    }
    console.log(data);
    callback(data);
  });
};

Now I am trying to write a function that will basically take two different files in txt that contains numbers for example:

files.txt content would have the numbers:

2 3 4 5

files2.txt content would have the numbers:

5 6 2 7

Where I am confused is implementing the function to get the sum of both files

const sumTheFiles = function (file1, file2){
let num1 = read(file1)
let num2 = read(file2)
let sum = num1   num2
return sum
}

Can I get some advice on this on how I would tackle this. I have no idea what to do I am currently stuck

Thanks!

CodePudding user response:

The best way would be to use fs.promises instead, so you can Promise.all.

const sumTheFiles = function (file1, file2){
  Promise.all([file1, file2].map(
    filename => fs.promises.readFile(filename, 'utf-8')
  )
    .then(([result1, result2]) => {
      // do stuff with file content result1 and result2
    })
    .catch(handleErrors); // don't forget this part
};

If you have to use the callback versions, you can assign to an outside variable, and check if the other one is populated.

const sumTheFiles = function (file1, file2){
  let r1;
  let r2;
  read(file1, (data) => {
    r1 = data;
    if (r2) finish();
  });
  read(file2, (data) => {
    r2 = data;
    if (r1) finish();
  });
  const finish = () => {
    // do stuff with r1 and r2
  };
}

CodePudding user response:

I found the solution after playing with the way the fs.readFile was position in the code. All I did was repeat the fs.readFile

const sumTheFiles = function(file1, file2, callback) {
  fs.readFile(file1, "utf8", (err, data) => {
    if (err) {
      callback(err, null);
    } else {
      let num1 = data;
      fs.readFile(file2, "utf8", (err, data) => {
        if (err) {
          callback(err, null);
        } else {
          let num2 = data;
          const sum = Number(num1)   Number(num2);
          callback(null, sum);
        }
      });
    }
  });
};
  • Related