javascript - NodeJS : Append file inside a callback function

标签 javascript node.js asynchronous electron fs

我有一个 Electron JS 应用程序,它启动我用 C++ 编写的独立子进程(非阻塞)(二进制应用程序)。

我希望将 C++ 标准输出 [STDOUT] 流式传输到 NodeJS 并将其记录在日志文本文件中。

我已经看到了使用 spawn() 之间的差异, fork() , exec()execFile()在 NodeJS 子进程文档 (link here) 中。就我而言,我需要使用 spawn()方法。

这是我的 Electron JS/NodeJS 代码:

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

这段代码实际上有效,并且它将 C++ 输出记录在 log_timestamp.txt 中。文件。

我的问题

当我调用这个 NodeJS 文件时,ElectronJS Web 界面和浏览器控制台在无限刷新循环中每秒刷新很多次。因此,每次 Electron JS 刷新页面时,NodeJS 都会启动再次一个新的子进程。 最后,我得到了很多log_timestamp.txt 几秒钟后。

如果我只删除 fs.appendFile()并将其替换为 console.log(data)我只得到了一次所需的控制台日志输出,没有页面刷新或异常行为。 示例:

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

我做错了什么? 如何修复第一个源代码以在文本文件中正确记录 C++ 输出?

我的系统是:

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

更新 1

按照@Jonas的建议,我尝试了这个替代代码,但我得到了相同的异常行为。

// 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));

最佳答案

流的要点在于,您可以将它们通过管道连接在一起,然后让引擎处理所有其余的事情:

 child.stdout.pipe(fs.createWriteStream(/*...*/));

我认为您的主要问题是 appendFile 必须打开文件,锁定它,写入它,解锁它,并且这发生在每个数据 block 上。这会减慢写入速度,并且由于您没有正确处理背压,内存消耗开始增加,并可能导致您看到的滞后。

关于javascript - NodeJS : Append file inside a callback function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59107171/

相关文章:

javascript - Node.js 的 Hip-Hop PHP?

javascript - react : apply multiple filters to array

http-headers - 如何使用 cookie 创建 HTTP 客户端请求?

javascript - 套接字多次发出事件

javascript - 具有完整路径的 Node 异步 mkdir

c# - 如何使用await关键字?

api - 无法在itemCount中获取数据长度

javascript - 将数据放在 firebase 数据库中多个位置的最佳方法

javascript - Jquery 验证器插件不检查新输入

javascript - 如何将特定对象值插入数组