php和NodeJs共存的demo开发环境

php和NodeJs共存的开发环境

什么?有这样的需求吗

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';

Author: tom

Date: 2012-08-21 23:44:28 CST

HTML generated by org-mode 6.33x in emacs 23

原文地址:https://www.cnblogs.com/wewe/p/2650055.html