php和NodeJs共存的開發環境
什么?有這樣的需求嗎
Table of Contents
1 折騰 php nodejs 到一起
nodejs當然很火,就像着火了一樣,但是必須承認要搭建一個前端的demo開發環境還是PHP靠譜, windows下可以非常的集成套件,比如http://www.apachefriends.org/zhcn/xampp.html, PHP語言本身就是一個強大的模板,寫demo時,共用頭尾,可以通過include和require引入,可以內嵌 循環生成一些dom結構,相較而言,node還是不那么方便的。
既然PHP已經那么方便了,可是為什么還是要跟node一起用呢,真的有點為了用而用了……
2 how?
如你安裝了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混搭的服務器就搭建成功了
3 注意點
3.1 請求和響應數據須是Buffer對象
response.write(new Buffer(chunk)) proxy_request.write(new Buffer(chunk));
3.2 要想傳遞表單數據,需要在header設置
headers['Content-Type']= 'application/x-www-form-urlencoded';
Date: 2012-08-21 23:44:28 CST
HTML generated by org-mode 6.33x in emacs 23