Node.js 寫HTTP伺服器:實作紀錄

Node.js 利用Express來寫HTTP伺服器     :   實作紀錄


Node.js專案開發習慣
config : 專案通用設定(DB設定………..等等)
modeules (M): 功能模組(商業邏輯……等等)                     
public (V): 網頁
routes (C): 前後端媒合設定




Package.json : 專案使用的套件設定檔,建立於專案目錄下
執行 npm install 會將所需套件建立
$ npm install
 {   //程式註解
"name": "obapp",
     "version": "0.0.1",
     "private": true,
     "scripts": {
          "start": "node server.js"
     },
     //專案使用到的套件設定
         //“package name”:”版本
     "dependencies": {
          "express": "3.2.6",
          "jade": "*",
          "mongodb": "*",
          "mongoose":"*",
          "request":"*",
          "cheerio":"*",
          "iconv-lite":"*",
          "moment":"*",
          "async":"*"
     }
}



 Server.js : node.js 執行檔
建立Http 伺服器,將使用到express fs(包含在node.js裡面,不須額外安裝) 套件

var express = require('express');
var fs      = require('fs');

//******************
var app = express()
     , http = require('http')
     , path = require('path');



var models_dir = __dirname + '/modules';

//console.log(fs.readdirSync(models_dir));
fs.readdirSync(models_dir).forEach(function (file) {
     if(file[0] === '.') return;
     if(fs.statSync(models_dir+'/'+file).isDirectory()) {//如果是目錄    
     }else{
         require(models_dir+'/'+ file);
     }   
});
//FB confing
fs.readdirSync(models_dir+"/fb/conf").forEach(function (file) {
     if(file[0] === '.') return;    
     require(models_dir+'/fb/conf/'+ file);
});
//FB db
fs.readdirSync(models_dir+"/fb/db").forEach(function (file) {
     if(file[0] === '.') return;    
     require(models_dir+'/fb/db/'+ file);
});

app.configure(function () {
     app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 8080);
     app.set('node_ip',process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");
//   app.set('views', __dirname + '/app/views');
//   app.set('view engine', 'jade');
     app.use(express.logger('dev'));               //設定log
     app.use(express.cookieParser());                  //解析表頭裡的cookie
     app.use(express.json());                          //解析json格式
app.use(express.urlencoded());                    //解析網址格式
    
app.use(express.bodyParser());
 
// is equivalent to:
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());

     app.use(express.methodOverride());
    
     app.use(app.router);                              //使用router
     app.use(express.static(path.join(__dirname, 'public')));//可運行的靜態頁面
    
});

app.configure('development', function () {
     app.use(express.errorHandler());
});

require('./config/routes')(app);              //routes引用近來
//建立http server 並監聽
http.createServer(app).listen(app.get('port'),app.get('node_ip'), function () {
  console.log("Express server listening on port " + app.get('node_ip') + ":" + app.get('port'));
});




Config :
Config.js

module.exports = {
        fbdb:{
                db_uri: "mongodb://127.0.0.1:27017/fb",
                db_options: {
                        db: { native_parser: true },
                        server: { poolSize: 5 }
                },
        },
        etdb:{
                db_uri: "mongodb://192.168.48.111:27017/et",
                db_options: {
                        db: { native_parser: true },
                        server: { poolSize: 5 }
                },
        },
        facebook: {
                clientID: "{{PLACEHOLDER}}",
                clientSecret: "{{PLACEHOLDER}}",
                callbackURL: "{{PLACEHOLDER}}"
        },
        google: {
                clientID: "{{PLACEHOLDER}}",
                clientSecret: "{{PLACEHOLDER}}",
                callbackURL: "{{PLACEHOLDER}}"
        },
       
};

Routes.js

module.exports = function(app){
     require('../routes/rtest.js')(app);
    
};



Modeules :
Test.js

var moment = require('moment');
moment.locale("zh-tw");

exports.sayHi = function(param,done) {
     console.log(param);   
     var dt = moment().format("YYYY-MM-DD HH:mm");
     if (typeof(param) !== "undefined") {
         var docs = {
              name : param.name,
              dt : dt,
         };      
         done(null, docs);
     }else{
         var docs = {
              name : "沒有名字",
              dt : dt,
         };
         done(null, docs);
     };
} ;



Routes :
Rtest.js

var route = require('../modules/test');

module.exports = function(app) {
    
     app.post("/do_sayhi", function(req, res) {
//       console.log(req.body);
         route.sayHi(req.body,function(err, doc){
              if(err)  throw err;
              console.log(doc);
              return res.json(200, {
                  message : "ok",
                  data : doc
              });
         });
     });
    
};




Public :

Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
     <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
     <script src="js/index.js"></script>
</head>
<body>
     <div class="ui-widget">        
       <label>姓名:</label>
       <input type="text" id="name">
       <button id="doact">送出</button>
     </div>
     <div id="output"></div>
</body>
</html>




Index,js

$(document).ready(function(){  
     $('#doact').on('click', dosayhi);   
});

var serverBaseUrl = "http://"+location.host;

function dosayhi() {
     var name = $("#name").val();
     $.ajax({
         url : serverBaseUrl+'/do_sayhi',
         //async: false,
         type : 'POST',
         dataType:"json",
         data: {
              name : name
         },
         success : function(smsg) {
              if(smsg.message) {
                  var docs = smsg.data;
                  var name = docs.name;
                  var dt = docs.dt;
                  $("#output").html(dt + " : " +name + " say hi");
              }            
         },
         error : function( jqXHR , textStatus, errorThrown ) {
              console.log(jqXHR);
              console.log('jqXHR=', jqXHR.status);
              console.log('textStatus=', textStatus);
              console.log('cerrorThrown=', errorThrown);
         }
     });
    
}




開始執行

npm install     --> 將package.json  內的套件載入

node server.js   --> 啟動 http server



參考文件


exports VS module.exports
使用外部檔案
要寫出模組化的程式就必須把程式切分的乾淨. node.js 遵照 CommonJS 的慣例,  require 以及exports 來作檔案和模組之間的溝通.

exports寫法有兩種 :
1.module.exports
   將所有的功能寫入在同一個結構內。
   EX : mod.js
    module.exports = {
       do_a : function(){
            // do something ...
       },
       do_b : function(){
           // do something ...
       }
    };

2.exports
   一個功能一個功能分開寫。
   EX : mod.js
    exports.do_a = function(){
        // do something ...
    };

    exports.do_b = function(){
        // do something ...
    };

呼叫使用方,兩種都一樣。
var mod= require( './mod' );
mod.do_a();

mod.so_b();

留言

這個網誌中的熱門文章

Tomcat 7.0 JDBC Connection Pool 帳號密碼加密

PM2 (node.js 管理套件) 安裝使用

vb6動態載入ocx控制項