【发布时间】:2020-03-25 04:36:20
【问题描述】:
我有一个 Electron JS 应用程序,它启动了一个我用 C++ 编写的独立子进程(非阻塞)(二进制应用程序)。
我希望将 C++ 标准输出 [STDOUT]流式传输到 NodeJS 并将其记录到日志文本文件中。
我已经在 NodeJS 子进程文档 (link here) 中看到了使用 spawn()、fork()、exec() 和 execFile() 之间的区别。就我而言,我需要使用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++ 输出?
我的系统是:
- 电子 7.1.2
- 节点 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));
【问题讨论】:
标签: javascript node.js asynchronous electron fs