nodejs和python和php_PHP和Nodejs能配合使用吗?
可以
如你安裝了Python,可以立馬執行一個簡單的命令,一個簡便的開發服務器就完成了。python -m SimpleHTTPServer
但是PHP,直到php5.4才支持類似的功能
$ php -S 0.0.0.0:8000
PHP 5.4.0 Development Server started at Tue Aug 21 23:21:50 2012
Listening on 0.0.0.0:8000
Document root is /home/tom
Press Ctrl-C to quit.
php本身就可以架一個服務器,Nodejs也可以架一個服務器,那么就不用啥apache啦,nginx啦
基本思路就是Node開啟一個服務器作為前臺,監聽80端口,類似Apache的角色,php開啟一個服務器在后臺運行。 Node服務將http請求轉發給php服務器執行,執行完成后返回給node服務器,node服務器再返回給瀏覽器
Node承擔的是一個中間的代理角色
var fs = require('fs'),
http = require('http'),
spawn = require('child_process').spawn,
phpserver;
phpserver = spawn('php',['-S','0.0.0.0:8000']);
phpserver.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
phpserver.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
phpserver.on('exit', function (code) {
console.log('child process exited with code ' + code);
});
process.on('exit',function(){
phpserver.kill('SIGHUP');
});
function handleRequest(request, response) {
var headers = {};
for(var x in request.headers){
headers[x] = request.headers[x];
}
headers['Content-Type']= 'application/x-www-form-urlencoded';
var proxy_request = http.request({
host:'localhost',
port:8000,
method:request.method,
path:request.url,
headers:headers
});
proxy_request.on('response', function (proxy_response) {
response.writeHead(proxy_response.statusCode,proxy_response.headers);
proxy_response.on('data', function(chunk) {
response.write(new Buffer(chunk));
});
proxy_response.on('end', function() {
response.end();
});
});
request.on('data', function(chunk) {
proxy_request.write(new Buffer(chunk));
});
request.on('end', function() {
proxy_request.end();
});
}
http.createServer(handleRequest).listen(80);
保存上面的文件為server.js然后在命令行里執行
node server.js
一個node和php混搭的服務器就搭建成功了
總結
以上是生活随笔為你收集整理的nodejs和python和php_PHP和Nodejs能配合使用吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 10691020008是平安吗
- 下一篇: 13薪的发放标准 是不是必须发的福利