Abdullah Ch
Abdullah Ch

Reputation: 2181

How to write to a file in a Big loop using Javascript

My code is

for (let indexM = 0; indexM < 0.5; indexM += 0.01) {
  //C
  for (let indexC = -10; indexC < 10; indexC += 0.05) {
    //X
    for (let indexX = 0; indexX < X.length; indexX++) {
      //Y = M * X[i] + C
      PredictedY = indexM * X[indexX] + indexC;
      Error += (PredictedY - Y[indexX]) * (PredictedY - Y[indexX]);
    }
    newMeanSquareError = Error / X.length;

    let M = indexM.toFixed(2);
    let C = indexC.toFixed(2);
    let MSE = newMeanSquareError.toFixed(2);

    // var data = `M slope: ${M} ` + `  Y-intercept: ${C} ` + `  MSE: ${MSE} ` + "\r\n";

    fs.writeFile(
      "HouseSales.txt",
      `M Slope : ${M}  C Intercept : ${C} MSE : ${MSE}`,
      (err) => {
        // In case of a error throw err.
        if (err) throw err;
      }
    );

    if (least > newMeanSquareError) {
      least = newMeanSquareError;
      newC = indexC;
      newM = indexM;
    }
    Error = 0;
  }
}

I am getting this error


[Error: EMFILE: too many open files, open 'F:\Semester 5\Introductiob to AI\Lab1\HouseSales.txt'] {
  errno: -4066,
  code: 'EMFILE',
  syscall: 'open',
  path: 'F:\\Semester 5\\Introductiob to AI\\Lab1\\HouseSales.txt'
}

Is there any way where I can write to a file in a very big loop in JavaScript ? I have tried fs but I am not getting a solution. I think fs cannot help when it comes to writing to a file 1000s of times or more.

Upvotes: 1

Views: 933

Answers (1)

audzzy
audzzy

Reputation: 741

you should create a stream before the loop and write to it in he loop:

var out = fs.createWriteStream("HouseSales.txt", { flags : 'a' });

a flag is for appending, it will create the file if it doesnt exist. and use this to write:

out.write(`M Slope : ${M}  C Intercept : ${C} MSE : ${MSE}`, 'utf-8');

finally (after the loop) close the stream:

out.end();

Upvotes: 3

Related Questions