如何从PHP脚本运行Nodejs服务器? [英] How to run Nodejs Server from PHP script?

查看:678
本文介绍了如何从PHP脚本运行Nodejs服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主要应用程序是PHP服务器。
我有一个作为子应用程序的Nodejs服务器。

I have a PHP server which is the main application. I have a Nodejs Server which is a sub-application.

Nodejs服务器用于通知机制。我希望能够从运行在PHP上的主应用程序禁用通知机制。

Nodejs Server is used for a Notification Mechanism. I want to be able to disable the notification mechanism from my main application which runs on PHP.

有一个按钮。单击它后,我更改了Nodejs配置文件,现在我想重新启动Nodejs服务器。
我想我可以在PHP中执行以下操作:

There is a button. On clicking it, I change my Nodejs config file and now I want to restart Nodejs server. I imagine I can do something like this in PHP:

exec( kill sudo lsof -t -i:4849 );
exec( node server.js);

exec("kill sudo lsof -t -i:4849"); exec("node server.js");

可能出现的问题:
1)权限问题:我想可以通过给我apache用户节点应用程序的所有权。我对吗?
2)Exec:执行一个exec会导致我的浏览器继续加载。我执行netstat并发现Nodejs服务器正在运行。这是令我担忧的问题。我想我需要做一些fork和exec方法,以便子进程(Nodejs)独立运行。

Prospective problems: 1)Permissions issue : I imagine this could be solved by giving my apache user the ownership of node application. Am I right? 2)Exec : Doing an exec causes my browser to go on loading. I do netstat and find the Nodejs server running. This is the problem that is worrying me. I suppose I need to do some fork and exec method so that the child process(Nodejs ) runs independently.

请帮助。

解决方案:

    exec("fuser -k ". NODEAPPPORT ."/tcp > /dev/null 2>&1 &");
    exec('bash -c "exec nohup setsid node "'.NODEPATH.'/app.js" > 
    /dev/null 2>&1 &"');

我将stdout和stderr重定向到/ dev / null。
我将其作为一个独立的进程运行。它的工作原理就像一个魅力。

I redirected the stdout and stderr to /dev/null. I run it as an independent process.It works like a charm.

推荐答案

我的建议是:
不要。

通过诸如表达或其他内容。然后,您可以通过专用网络公开您的Node应用程序的端点(这是最简单的解决方案IMO)和/或在PHP应用程序和Node应用程序之间使用简单的授权机制。然后,您可以通过该简单的API端点启动/停止通知系统,而不必每次都终止/重新启动Node应用程序。假设由于某种原因它在启动时崩溃,您将无法判断它是否已从PHP应用程序中退出。

Run the Node server as a standalone server, either through a framework such as Express or something else. You could then expose your Node app's endpoint(s) (which would be the simplest solution IMO) via a private network and/or use a simple authorization mechanism between your PHP app and your Node app. You can then start/stop the notification system via that simple API endpoint instead of killing/restarting your Node app every time. Suppose that it crashes upon startup for whichever reason, you wouldn't be able to tell that it's down from your PHP app.

我不知道您的通知应用程序是如何工作的,但是我猜它正在处理某种流,您可以在不杀死整个Node的情况下轻松关闭它服务器。

I don't know how exactly your notifications app works, but I'm guessing it's handling some sort of a stream which you can easily turn off without killing the entire Node server.

这篇关于如何从PHP脚本运行Nodejs服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆