我有一个 exe 文件,它执行一些操作,然后将结果写入日志文件。 我想激活exe,然后在完成后读取日志文件并分析它。
我的问题是:
假设 validate()
是读取日志文件并分析它的函数。如果我使用 child_process.exec('myExe.exe',validate);
它无法正常工作并引发异常,因为 Node 首先尝试打开日志文件,但它尚不存在。如果我尝试像
child_process.exec('myExe.exe');
validate();
同样的问题。
有什么想法如何首先运行 exe,然后[仅在完成后]分析日志文件?
编辑: 这不是一个代码问题。手动打开 exe,然后启动 Node 模块可以成功调用 validate() 而不会崩溃。这样做的副作用是 Node 现在锁定文件并且第二次运行的 exe 可以打开该文件。以下是 exe (C++) 和 Node 的代码: 执行:
#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
using std::string;
using std::ofstream;
int main(int argc, char** argv) {
srand(time(NULL));
int random = rand() % 11;
string output = random >=5 ? "GOOD" : "BAD";
ofstream fileWriter("output.txt",std::ofstream::out);
if (fileWriter.is_open()){
fileWriter << output;
fileWriter.close();
}
return 0;
}
Node :
var child = require('child_process');
var fs = require('fs')
var programPath = '<put your path here , I put my absolute path>'
var validate = function(){
var outputFile = fs.readFileSync(programPath+'\\output.txt').toString();
var compareFile = fs.readFileSync(programPath+'\\Compare.txt').toString();
if (outputFile == compareFile){
console.log('Success');
} else {
console.log('Failure');
}
}
var test = child.exec(programPath+'\\Scanner.exe',validate);
实际错误: 返回绑定(bind).open(pathModule._makeLong(path), stringToFlags(flags), mode); ^ 错误:ENOENT,没有这样的文件或目录“...\output.txt”
最佳答案
最终问题是这样的: 当 Node 打开一个进程时,它的打开方式就像 exe 在 Node 文件夹中一样。 EXE 会写入其位于 on 时所在的目录,即 Node 文件夹。 另一方面, Node 模块。有原始 EXE 文件的绝对路径,当它尝试打开日志文件时 - 它不在那里,它位于 Node 文件夹中。 解决方案是将 'cwd' 参数传递给 child_process.exec :
var test = child.exec(programPath+'\\Scanner.exe', { cwd: programPath }, validate);
关于javascript - child_process.exec 与外部 EXE 文件同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28629099/