結合node.js和postgresql,創建一個demo

模型簡介:用node.js創建一個http服務器,使用瀏覽器訪問相應的地址,顯示數據庫信息。

   注:該demo建立得比較簡單,數據庫操作就是查詢某張表的數據,然後將查詢出來的數據以JSON格式顯示在瀏覽器上

1)流程簡介
  該demo一共包含4個文件:index.js   server.js    router.js    function.js
  其中index.js中連接了數據庫,連接成功後,調用server啓動函數。
      server.js 創建http服務器,並指定端口。
      router.js 路由器,根據url地址,調用不同的函數
      function.js 各個函數的具體實現(此demo中只有一個)

2)  代碼實現

  index.js

//加載相應的模塊,這兒使用的是postgresql數據庫,因此加載的模塊是pg。使用不同的數據庫可以加載相應
的模塊
var pg = require('pg');

//加載內部模塊
var server = require("./server");
var router = require("./router");
var func = require("./function");

//將url路徑對應到相應的函數
var handle = {};
handle["/"] = func.select;
handle["/select"] = func.select;

//構造連接數據庫的連接字符串:"tcp://用戶名:密碼@ip/相應的數據庫名"
var conString = "tcp://postgres:postgres@localhost/my";
var client = new pg.Client(conString);  //構造一個數據庫對象

//連接數據庫,連接成功,執行回調函數
client.connect(function(error, results) {
     if(error){
            console.log('ClientConnectionReady Error: ' + error.message);
            client.end();
            return;
        }
        console.log("client.connect OK.\n");
    server.start(client,router.route,handle); //啓動server
});

server.js

//加載對應的模塊
var http = require("http");
var url = require("url");

function start(client,route,handle)
{
    //創建http服務器
    http.createServer(function(request,response){
        var pathname = url.parse(request.url).pathname;
        console.log("Request for " + pathname + " received.");
        route(client,handle,pathname,response);
    }).listen(8888);   //指定端口

    console.log("Server has started.");
}

exports.start = start;

router.js

function route(client,handle,pathname,response){
    console.log("About to route a request for " + pathname);

    if(typeof handle[pathname] === 'function'){
        handle[pathname](client,response);  //執行對應的函數
    }else{
        console.log("No request handle found for " + pathname +'\n');
        response.writeHead(404,{"Content-Type":"text/plain"});
        response.write("404 Not found");
        response.end();
    }
}

exports.route = route;

function.js

function select(client,response)
{
    console.log("Request handler 'select' was called.");
    //執行相應的sql語句
    client.query("select * from teacher;",function(error,results){
        console.log("in callback function.\n");
        if (error)
        {
            console.log("error");
            console.log('GetData Error: ' + error.message);
            client.end();
            return;
        }
        if(results.rowCount > 0)
        {
            //callback(results);
            //指定爲json格式輸出
            response.writeHead(200,{"Content-Type":"application/json"});       

            //先將results 字符串內容轉化成json格式,然後響應到瀏覽器上

 response.write(JSON.stringify(results)); response.end(); } });}

exports.select = select;



3) 執行結果

  (1)  http://localhost:8888/select

        1) 後臺顯示:

                client.connect OK.

                Server has started.

                Request for /select received.

                About to route a request for /select

                Request handler 'select' was called.

                in callback function.

       2) 瀏覽器顯示:

              {

                  "command":"SELECT",

                  "rowCount":2,

                   "oid":null,

                   "rows":

                          [

                                {

                                         "id":"1",

                                          "name":"aaa",

                                           "pwd":"111"

                                },

                                {

                                         "id":"2",

                                         "name":"bbb",

                                          "pwd":"222"

                               }

                            ]

                     }

(2)  http://localhost:8888/

        1) 後臺顯示:

                client.connect OK.

                Server has started.

                Request for /  received.

                About to route a request for /

                Request handler 'select' was called.

                in callback function.

       2) 瀏覽器顯示:同上   //由於在index.js文件中指定兩種情況都訪問同一個函數



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章