[EC2]用node.js存取mysql

LINEで送る
[`evernote` not found]

除了能取出資料外,轉成json來處理當然會比較方便嚕。所以首先檢查一下node.js的最新版本,升級後再安裝node-mysqlJSON-js

# wget http://nodejs.org/dist/v0.8.11/node-v0.8.11.tar.gz
# tar zxvf node-v0.8.11.tar.gz
# cd node-v0.8.11
# ./configure
# make
# make install
# which node
/usr/bin/node
# node -v
v0.8.11
# which npm
/usr/bin/npm
# npm -v
1.1.62
# npm install socket.io

接著就找個資料夾建立index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var http = require('http');
var mysql = require('mysql');
require('../../node_modules/json/json2');
http.createServer(function(request, response) {
        var mysql      = require('mysql');
        var connection = mysql.createConnection({
                user     : 'node',
                password : 'password',
                port: '/var/lib/mysql/mysql.sock',      // 使用sock連線
                database: 'nodeDB'
        });
 
        connection.connect();
 
        connection.query('SELECT * from ref_myData', function(err, results, fields) {
                if (err) throw err;
 
                // 轉換成JSON格式
                var data = JSON.stringify(results);;
 
                // HTTP回應
                response.writeHead(200, {'Content-Type': 'text/plain'});
                response.write(data + "\n");
                response.end();
 
                console.log(data);
        });
 
        connection.end();
}).listen(9008);
console.log('Server running at http://xxx.xxx.xxx.xxx:9008');

9008是我隨便開的port,只要在防火牆上有開就行了。而且不要使用原本有在使用的port,不然有可能會出現Error: listen EADDRINUSE的錯誤訊息。(資料參考)