Append file inside a callback function

I have a Electron JS app that starts a independent child process (non-blocking) (binary application) that I wrote in C++.

I would like to stream the C++ standard output [STDOUT] to NodeJS and log it in a log text file.

I already saw the differences between using spawn() , fork() , exec() and execFile() in the NodeJS Child Process documentation (link here). In my case, I need to use the spawn() method.

So here is my Electron JS / NodeJS code:

const path = require('path');
const fs = require("fs");
const cp = require("child_process");

[... another stuffs ...]

// Start a child process:
const child = cp.spawn(my_binary, ["param1", "param2", "param3"], { detached: true });
child.unref();

// STDOUT listener:
child.stdout.setEncoding('utf8');
child.stdout.on("data", (data) => {

    // Set the log file path:
    let filePath = path.join(__dirname, "..", "logs", logFilename);

    // Try to append: I GOT A REFRESH PAGE LOOP HERE:
    fs.appendFile(filePath, data, (err) => {
        if (err) {
            console.error("[STDOUT]", err);
        } else {
            // Get the C++ STDOUT output data:
            console.log(data);
        }
    });
})

This code actually works and it log the C++ output in a log_timestamp.txt file.

My problem

When I call this NodeJS file, the ElectronJS web interface and browser console refreshs a lot of times per second in a infinite refresh loop. So, each time that Electron JS refreshes the page, NodeJS starts again a new child process. Finally, I get a lot of log_timestamp.txt in a few seconds.

If I remove only the fs.appendFile() and replace it by console.log(data) , I got my desired console log output just one time, without page refreshes or anormal behaviors. Exemple:

const path = require('path');
const fs = require("fs");
const cp = require("child_process");

[... another stuffs ...]

// Start a child process:
const child = cp.spawn(my_binary, ["param1", "param2", "param3"], { detached: true });
child.unref();

// STDOUT listener:
child.stdout.setEncoding('utf8');
child.stdout.on("data", (data) => {

    // Set the log file path:
    let filePath = path.join(__dirname, "..", "logs", logFilename);

    // Get the C++ STDOUT output data:
    console.log(data);
})

What m’I doing wrong? How can I fix the first source-code in a way to log correctly the C++ output in a text file?

My system is:

  • Electron 7.1.2
  • Node 12.13.0
  • Windows 10 x64 and Ubuntu 18 x64

UPDATE 1

Following the @Jonas suggestion, I tried this alternative code, but I got the same anormal behavior yet.

// Start a child process:
const child = cp.spawn(bin, ["param1", "param2", "param3"], { detached: true });
child.unref();

// STDOUT listener:
child.stdout.setEncoding('utf8');
child.stdout.on("data", (data) => {
    console.log(data);
})

let filePath = path.join(__dirname, "..", "logs", logFilename);
child.stdout.pipe(fs.createWriteStream(filePath));