如何利用php执行nodejs文件

2025-06-23 10:45:48
推荐回答(2个)
回答1:

一,安装DNode,
1, for nodejs, 执行

$ sudo npm install dnode

2, for php, 利用composer来安装DNode php
执行下列语句下载composer

$ wget http://getcomposer.org/composer.phar
创建一个文件composer.json,然后填入如下语句,

{
"require": {
"dnode/dnode": "0.2.0"
}
}
执行如下语句安装,

$ sudo php composer.phar install

二,利用nodejs创建简单server程序, server.js

var dnode = require('dnode');
var server = dnode({
zing: function (n, cb) { cb(n * 100) }
});
server.listen(7070);
三,利用php创建客户端程序client.php, 其中需要引用刚才安装的dnode文件夹里面的文件autoload.php

// Connect to DNode server running in port 7070 and call
// Zing with argument 33
require 'lib/vendor/autoload.php';

// This is the class we're exposing to DNode
class Temp
{
// Compute the client's temperature and stuff that value into the callback
public function temperature($cb)
{
}
}

$loop = new React\EventLoop\StreamSelectLoop();
$dnode = new DNode\DNode($loop, new Temp());
$dnode->connect(7070, function($remote, $connection) {
// Remote is a proxy object that provides us all methods
// from the server
$remote->zing(33, function($n) use ($connection) {
echo "n = {$n}\n";
// Once we have the result we can close the connection
$connection->end();
});
});
$loop->run();
?>

回答2:

/**
* 返回的汉语文字信息在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;
}