[英]Executing nodejs script file in PHP using exec()
In my Application, I want to execute a Node.JS file from PHP which in turn makes an HTTP request to another PHP file.在我的应用程序中,我想从 PHP 执行一个 Node.JS 文件,该文件又向另一个 PHP 文件发出 HTTP 请求。
In short this is the Process that I am doing.简而言之,这就是我正在做的流程。
PHP file--->calls--> Nodejs file--->processes data -->and makes http request to-->PHP File PHP文件--->调用-->Nodejs文件--->处理数据-->并发出http请求到-->PHP文件
When I run the nodejs file via terminal, it successfully makes the http request to another PHP file and I get what I want.当我通过终端运行 nodejs 文件时,它成功地向另一个 PHP 文件发出了 http 请求,我得到了我想要的。
But, when I try to run the nodejs file through PHP, the nodejs files is not able to find some modules.但是,当我尝试通过 PHP 运行 nodejs 文件时,nodejs 文件无法找到某些模块。
My code in PHP:我在 PHP 中的代码:
$nodeJsPath = '/var/www/html/projectfolder/js/nodefunc.js';
$ret = exec("node ".$nodeJsPath.' 2>&1', $out, $err);
This is the error that I am getting:这是我得到的错误:
Array
(
[0] => module.js:457
[1] => throw err;
[2] => ^
[3] =>
[4] => Error: Cannot find module 'some_module'
[5] => at Function.Module._resolveFilename (module.js:455:15)
[6] => at Function.Module._load (module.js:403:25)
[7] => at Module.require (module.js:483:17)
[8] => at require (internal/module.js:20:19)
[9] => at Object.<anonymous> (/var/www/html/projectfolder/js/nodefunc.js:5:9)
[10] => at Module._compile (module.js:556:32)
[11] => at Object.Module._extensions..js (module.js:565:10)
[12] => at Module.load (module.js:473:32)
[13] => at tryModuleLoad (module.js:432:12)
[14] => at Function.Module._load (module.js:424:3)
)
Your goal is to execute a node command after changing directory.您的目标是在更改目录后执行节点命令。 Thus, you will need to run multiple sequential commands via the PHP exec() function.
因此,您将需要通过 PHP exec() 函数运行多个顺序命令。
Commands:命令:
cd /var/www/html/projectfolder/js
node nodefunc.js 2>&1
This is possible by adding && or ;这可以通过添加&&或; in between the commands.
在命令之间。
$ret = exec("cd /var/www/html/projectfolder/js; node nodefunc.js 2>&1", $out, $err);
I got it finally.我终于明白了。 Its just ignorng the
NODE_PATH
variable for reasons unkown :(由于未知的原因,它只是忽略了
NODE_PATH
变量:(
In the Nodejs File I hade to give the absolute path of the module like this:在 Nodejs 文件中,我不得不像这样给出模块的绝对路径:
var request = require("/usr/lib/node_modules/request");
npm install
)npm install
)exec
in the node application current working directory:exec
:exec("cd ". dirname($nodeJsPath). " && node nodefunc.js 2>&1", $out, $err);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.