如何在共享托管中托管Node.Js应用程序

如何在共享托管中托管Node.Js应用程序

问题描述:

如何在共享托管中托管Node.Js应用程序

How to host a Node.Js application in a shared hosting

我想在共享托管中托管一个node.js应用程序.有没有人要引用任何参考文献或文档?

I want to host a node.js application in shared hosting. Does anyone have any reference or documentation to refer to?

您可以可以在典型的Linux,Apache和PHP(LAMP)共享主机上运行node.js服务器.即使NPM,Express和Grunt运行正常,我也已经成功安装了它.请按照以下步骤操作:

You can run node.js server on a typical shared hosting with Linux, Apache and PHP (LAMP). I have successfully installed it, even with NPM, Express and Grunt working fine. Follow the steps:

1)使用以下代码在服务器上创建一个新的PHP文件并运行它:

1) Create a new PHP file on the server with the following code and run it:

<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');

2)以相同的方式安装您的节点应用,例如jt-js-sample,使用npm:

2) The same way install your node app, e.g. jt-js-sample, using npm:

<?php
exec('node/bin/npm install jt-js-sample');

3)从PHP运行节点应用程序:

3) Run the node app from PHP:

<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=49999 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:49999/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
    //If couldn't connect, try increasing usleep
    echo 'Error: ' . curl_error($curl);
} else {
    //Split response headers and body
    list($head, $body) = explode("\r\n\r\n", $resp, 2);
    $headarr = explode("\n", $head);
    //Print headers
    foreach($headarr as $headval) {
        header($headval);
    }
    //Print body
    echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);

Voila!看看 PHP共享托管上的节点应用程序的演示.

编辑:我在GitHub上启动了 Node.php项目

I started a Node.php project on GitHub.