当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - child_process.exec synchronization with outer EXE file

问题描述:

I have an exe file that does some action, then writes the result to a log file.

I want to activate the exe, then after it's done read the log file and analyze it.

My problem is:

Let's say validate() is the function which reads the log file and analyzes it. If I use child_process.exec('myExe.exe',validate); it does not work properly and throws an exception, because Node first tries to open the log file, but it does not exist yet. If I try to do it synchronized like

child_process.exec('myExe.exe');

validate();

same problem.

Any ideas how to first run the exe, then [only after it's done] analyze the log file?

EDIT:

this is not a code question. opening the exe manually and then start the node module manages to call validate() without crash. the side affect of this is that node is now locking the file and the second-time-running exe can open the file. here are the code for both the exe (C++) and node:

Exe:

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

actual error:

return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);

^

Error: ENOENT, no such file or directory '...\output.txt'

网友答案:

Eventually the problem went like this: when Node opens a process, it's opened as if the exe were in the node folder. the EXE writes to the directory it's located when it's on , which the node folder. the node module, on the other hand . had absolute path to the original EXE file , and when it tries to open the log file - it's not there , it's in the node folder. the solution is to pass 'cwd' argument to the child_process.exec :

var test = child.exec(programPath+'\\Scanner.exe', { cwd: programPath }, validate);
分享给朋友:
您可能感兴趣的文章:
随机阅读: