# [EC2]用node.js存取mysql

- URL: https://justfly.idv.tw/ec2%e7%94%a8node-js%e5%ad%98%e5%8f%96mysql/
- 日期: 2012-10-12
- 分類: 瞎子摸OS
- 標籤: EC2, error, JSON, MySQL, node.js

除了能取出資料外，轉成json來處理當然會比較方便嚕。所以首先檢查一下node.js的[最新版本](http://nodejs.org/download/)，升級後再安裝[node-mysql](https://github.com/felixge/node-mysql)跟[JSON-js](https://github.com/douglascrockford/JSON-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:

```
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的錯誤訊息。([資料參考](http://www.koikikukan.com/archives/2012/01/10-015555.php))
