gpt4 book ai didi

node.js - 如何在共享主机中托管 Node.Js 应用程序

转载 作者:IT老高 更新时间:2023-10-28 21:47:33 25 4
gpt4 key购买 nike

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

我想在共享主机中托管一个 node.js 应用程序。有没有人有任何引用或文档可以引用?

最佳答案

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

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

<?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) 以相同的方式安装您的 Node 应用程序,例如jt-js-sample,使用 npm:

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

3) 从 PHP 运行 Node 应用程序:

<?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);

瞧!看看demo of a node app on PHP shared hosting .

编辑:我开始了 Node.php project on GitHub .

关于node.js - 如何在共享主机中托管 Node.Js 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24777750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com