2014年3月25日 星期二

在 CentOS 安裝 Node.js 及服務器測試程式

Install Node.js in CentOS with server sample code

一直都想試玩 Node.js,看看寫法、效能及維護比用開的 PHP 方式有甚麼不同。今天把它實現了。

在開始安裝 Node.js 之前,需要確保 CentOS 有相關工具。在 Terminal 安裝的指令如下:
yum install gcc gcc-c++
yum install autoconf automake make
yum install curl
yum install openssl-devel

穩陣起見,還是來過系統更新:
yum update

有了以上工具,下一歲是安裝 Node.js。先跳到打算安裝的目錄:
cd /etc/
mkdir nodejs
cd nodejs
wget http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz
tar zxvf node-v0.10.26.tar.gz
cd node-v0.10.26
./configure
make
make install
node --version

由於有機會用得上 Socket,還是把 socket.io 也一起安裝:
npm install socket.io

作為服務器,基本上也會使用到 MySQL,所以也要安裝接口:
npm install mysql

程序安裝完成。接著是編寫服務器的測試程式。把以下代碼儲存為 server-example.js:
//----------------------------------------------------------------------------------------
//  Node.js Server Test
//  Written by Pacess HO
//  Copyright 2014 Pacess HO.  All rights reserved
//----------------------------------------------------------------------------------------

var serverHost = "192.168.1.10";
var serverPort = 8888;

var sqlDatabase = "database";

//----------------------------------------------------------------------------------------
function getTimeStamp()  {
 var currentDate = new Date();

 var year = currentDate.getFullYear();
 var month = currentDate.getMonth()+1;
 var date = currentDate.getDate();
 var hour = currentDate.getHours();
 var minute = currentDate.getMinutes();
 var second = currentDate.getSeconds();

 var timeStamp = year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
 return timeStamp;
}

//----------------------------------------------------------------------------------------
function PHLog(message)  {
 var timeStamp = getTimeStamp();
 console.log(timeStamp+"> "+message);
}

//----------------------------------------------------------------------------------------
//  Create MySQL connection
var mysql = require("mysql");
var connection = mysql.createConnection({
 host: "127.0.0.1",
 user: "user",
 password: "password"
});

connection.connect();
connection.query("use "+sqlDatabase);

//----------------------------------------------------------------------------------------
//  Create HTTP server
var http = require("http");
var server = http.createServer(function(request, response)  {

 response.writeHead(200, {"Content-Type": "text/plain"});

 var url = require("url");
 var urlString = request.url;

 var urlQuery = url.parse(urlString, true).query;
 var action = urlQuery.action;

 var sqlQuery = "SELECT * FROM user"; 
 connection.query(sqlQuery, function(err, rowArray)  {
  if (err)  {throw err;}
  else  {

   for (var i=0; i<rowArray.length; i++)  {
    var row = rowArray[i];
    response.write(i+") "+JSON.stringify(row)+"\n");
   }

   var timeStamp = getTimeStamp();
   response.end(timeStamp+"> Done.\n");

   PHLog("Request done!");
  }
 });

 //----------------------------------------------------------------------------------------
 //  Shut down the HTTP server?
 if (action == "close")  {

  //  Finally, we can now end connection in two ways. Either use connection.end, or connection.destroy.
  //  connection.end statement will close the connection ensuring that all the queries in the queue are processed. Please note that this is having a callback function.
  //  connection.destroy statement will terminate the assigned socket and close the connection immediately. Also there is no more callbacks or events triggered for the connection.
  connection.end(function(err)  {

   //  MySQL connection closed, close server now
   server.close();
   PHLog("Server closed!");

   process.exit();
  });
 }
}).listen(serverPort, serverHost);

//----------------------------------------------------------------------------------------
console.log("\n\n\n");
PHLog("Server running at http://"+serverHost+":"+serverPort+"/");
以上程式會讀取 MySQL 內名為 database 的數據庫中的 user 表格。內容需要自行輸入。執行測試程式:
node server-example.js

打開瀏覽器,在地址列輸入 http://192.168.1.10:8888/ 會看到

沒有留言: