从PHP运行NodeJS命令

时间:2015-04-24 09:45:42

标签: php node.js

当用户单击本地Intranet页面上的按钮以运行某些Node JS命令时,我运行以下PHP代码。 e.g。

exec('npm install', $output);
$output = implode(PHP_EOL, $output);
echo $output;

但是命令似乎没有运行......如果我在命令提示符下输入命令并运行它就会这样...

我没有看到任何错误,并且NodeJS被设置为Path中的系统变量,因此它应该知道grunt是什么......任何想法?其他命令,例如whoami运行良好。

有什么想法吗?

我在Windows 7上。

更新:根据以下评论,我现在可以收到错误:

exec('npm install 2>&1', $output, $returnCode);
$output = implode(PHP_EOL, $output);
echo $output . ' ' . $returnCode;

这就是错误:

TypeError: Cannot call method 'get' of undefined at C:\Program Files (x86)\nodejs\node_modules\npm\lib\npm.js:310:23 at C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\npmconf\npmconf.js:80:7 at Array.forEach (native) at C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\npmconf\npmconf.js:79:13 at f (C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\once\once.js:16:25) at C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\npmconf\npmconf.js:108:14 at Conf. (C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\npmconf\npmconf.js:179:14) at Conf.next (C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\npmconf\lib\load-prefix.js:48:20) at C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\mkdirp\index.js:37:53 at Object.oncomplete (fs.js:107:15) C:\Program Files (x86)\nodejs\node_modules\npm\lib\npm.js:33 throw new Error('npm.load() required') ^ Error: npm.load() required at Object.npm.config.get (C:\Program Files (x86)\nodejs\node_modules\npm\lib\npm.js:33:11) at exit (C:\Program Files (x86)\nodejs\node_modules\npm\lib\utils\error-handler.js:49:27) at process.errorHandler (C:\Program Files (x86)\nodejs\node_modules\npm\lib\utils\error-handler.js:316:3) at process.emit (events.js:95:17) at process._fatalException (node.js:272:26) 7

所以看起来PHP知道NodeJS和NPM在哪里......但是无法运行它?

如果我在PHP中whoami得到nt authority\iusr

但是,如果我从命令提示符处执行此操作,那么我会得到:dom\cameron

我想知道是不是因为当我在命令提示符下直接运行它时,PHP会以不同的用户身份运行...

3 个答案:

答案 0 :(得分:1)

好的,我已经成功解决了这个问题!

基本上你需要运行网站(PHP文件所在的位置)作为运行NodeJS的用户!

为实现这一点,我在IIS中执行了以下操作:

1.) Find the website
2.) Choose basic settings
3.) Click the connect as... button
4.) Choose 'specific user'
5.) Enter `dom/cameron` and my password
6.) Restart IIS

如果有人对如何让NodeJS运行默认nt authority\iusr有任何想法,那么随时发布答案:)

答案 1 :(得分:0)

您在WINDOWS路径中定义了npm,但PHP是否识别它?

我建议你应该在exec中编写完整的NPM路径来测试它。如果它有效,那么在执行npm install之前,应该使用正确的参数调用 putenv() ..

首先尝试:

exec('C:\npm-test\npm install', $output);
$output = implode(PHP_EOL, $output);
echo $output;

如果可行,请在调用exec()之前使用putenv()命令。例如:

putenv("npm='C:\npm-test\npm'");

//然后执行exec(...)

答案 2 :(得分:0)

您收到的错误表明未定义对象。很可能一个模块根本没有加载,因为你没有从正确的位置运行脚本,而且某些包含的相对链接无法正常工作。以正确的用户身份运行可能会修复它。或者在运行节点脚本之前尝试更改到正确的目录。或者更改节点脚本中链接的位置。