Home >Backend Development >PHP Tutorial >node.js - 如何利用php执行nodejs文件

node.js - 如何利用php执行nodejs文件

WBOY
WBOYOriginal
2016-06-06 20:35:462318browse

如何利用php 的exec执行nodejs文件? 如下执行却执行失败

<code>        public function execTask ($dirPath)
        {
            $serverPath = self::$serverPath;
            exec("node httpd.js $serverPath",$info, $val);
            var_dump($info);
            echo "$val";
        }
</code>

如果仅仅是exec("node -v $serverPath",$info, $val);却可以输出版本号,执行成功。求解答,谢谢。

回复内容:

如何利用php 的exec执行nodejs文件? 如下执行却执行失败

<code>        public function execTask ($dirPath)
        {
            $serverPath = self::$serverPath;
            exec("node httpd.js $serverPath",$info, $val);
            var_dump($info);
            echo "$val";
        }
</code>

如果仅仅是exec("node -v $serverPath",$info, $val);却可以输出版本号,执行成功。求解答,谢谢。

你可以换成 shell_exec 试试

我也有类似的用法,所以除了有能读出消息的之外,还有能直接后台执行的功能,都是通过进程实现的

<code>/**
* 返回的汉语文字信息在windows中是GB2312编码,需要手动改成UTF8
*  iconv("GB2312","UTF-8",$read);
* @param $cmd
* @return array
*/
public function execFront($cmd)
{
    $response = array();
    $handle = popen("$cmd 2>&1", 'r');

    while ($read = fread($handle, 20096)) {

        if(!mb_detect_encoding($read, 'UTF-8', true))
            iconv("GB2312","UTF-8",$read);

        $response[] = trim($read);
    }
    pclose($handle);
    flush();

    return $response;
}

/**
 * @param $cmd
 */
public function execBackend($cmd)
{
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start cmd /c ". $cmd, "r"));
    }
    else {
        exec($cmd . " > /dev/null &");
    }

    return;
}
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn