記錄在 CentOS 上從源碼編譯安裝 Node.js、npm 及 MongoDB 驅動,並驗證連接數據庫的完整流程。
wget https://www.python.org/ftp/python/3.2.2/Python-3.2.2.tgz
tar xzvf Python-3.2.2.tgz
cd Python-3.2.2
./configure && make && make test && make install
註:CentOS 6 默認 Python 2.4,需手動升級。CentOS 7+ 已內建 2.7,可跳過。
wget https://github.com/joyent/node/tarball/master -O node.tar.gz
tar xzvf node.tar.gz
cd joyent-node-*
./configure --prefix=/opt/node/
make && make install
ln -s /opt/node/bin/node /usr/bin/node
ln -s /opt/node/bin/node-waf /usr/bin/node-waf
curl https://npmjs.org/install.sh | sh
npm install mongodb
cd node_modules/mongodb && bash ./install.sh
注意:驅動安裝在專案目錄 node_modules,非全局。
var http = require('http');
var mongodb = require('mongodb');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
mongodb.connect('mongodb://localhost:40202/log', function(err, conn) {
conn.collection('log', function(err, coll) {
coll.count({action: 772}, function(err, count) {
res.write('The total of action 772 is ' + count + '\n');
res.end();
});
});
});
}).listen(3000, '127.0.0.1');
console.log('Server running at https://127.0.0.1:3000/');
node mongo.js
# 瀏覽器訪問 https://127.0.0.1:3000
輸出統計結果,安裝驗證成功。
nvm 或二進制包安裝 Node LTS 版本,避免源碼編譯耗時且難維護。yum 源,直接 yum install mongodb-org 更簡單。pm2 / systemd 管理進程,配合日誌輪轉。筆記記錄的是早期版本流程,核心依賴關係至今未變,理解原理有助於排查環境問題。