NodeJS 从另一个脚本执行时,节点脚本不创建文件

xmjla07d  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(147)

我正在运行一个Express服务器,它通过POST请求接收JSON,然后将其保存到一个名为test.json的文件中,然后启动另一个名为demo.js的脚本,该脚本读取test.json,进行一些计算,然后在其工作目录中写入一个名为result.json的文件。此时,express服务器应该读取demo.js创建的result.json,然后将其发送回发出POST请求的服务器。
现在的问题是,如果我使用node demo.js命令直接从终端执行demo.js文件,它会创建文件,而当从Express服务器执行时,它会执行除文件创建之外的所有操作,因此服务器会抛出异常,因为它找不到必须作为POST请求的响应发送回来的文件。
下面是Express服务器的代码:

//Function that runs the demo.js script

function runScript(scriptPath, callback) {

// keeps track of whether callback has been invoked to prevent multiple invocatio>    var invoked = false;

var process = childProcess.fork(scriptPath);

// listen for errors as they may prevent the exit event from firing
process.on('error', function (err) {
    if (invoked) return;
    invoked = true;
    callback(err);
});

// execute the callback once the process has finished running
process.on('exit', function (code) {
    if (invoked) return;
    invoked = true;
    var err = code === 0 ? null : new Error('exit code ' + code);
    callback(err);
});

} app.post('/', (req, res) => { console.log("Received");

    fs.writeFile('./solver/src/test.json', JSON.stringify(req.body) , err => {
            if(err){
                    console.error(err);
            }
    });

    runScript('./solver/src/demo.js', function (err) {
            if (!err){
                    fs.readFile('./solver/src/result.json', (err, data) => {
                            if(err) throw err;

                            const jsonResp = JSON.stringify(data);
                            res.send(data);
                            console.log('finished running some-script.js');
                    });}
            else{
                    console.error(err);

            }
    });

});

这是demo.js文件

//result is a string generated by previous instructions //contained in the demo.js file, it gets correctly //printed by the console.log at the end of the script

fs.writeFile('./result.json', JSON.stringify(result) , (err) => { 
if(err){ console.error(err); } 
else{ console.log("File created succesfully"); } 
}); 
console.log(JSON.stringify(result, null, 1));

我尝试通过添加{flag来修改demo.js文件:'w'}在writeFile函数中无效。

tgabmvqs

tgabmvqs1#

通过使用完整路径('./solver/src/demo.js')调用fork,demo.js的当前工作目录就是express应用程序的当前工作目录。使用fork的cwd选项将fork进程的工作目录设置为'./solver/src/',您应该在预期的位置看到文件。

相关问题