Step 1 install nodejs
1.1 install nvm 使用 nvm(Node Version Manage) 來安裝 node.js,
sudo apt-get install git-core g++ curlgit clone git://github.com/creationix/nvm.git ~/.nvmecho ". ~/.nvm/nvm.sh" >> ~/.bashrc
重新開啟 terminal 或是在當前terminal 輸入:source ~/.bashrc或. ~/.bashrc 重新載入bashrc的設定到目前bash環境中。
1.2 install nodejs
nvm install v0.10.26nvm alias default v0.10.26node -v
PS:node.js 在 0.6.3 之後開始內建 npm (Node Package Management),
可用 npm -v 作確認。
Step 2 install express
Express是目前最流行的基於Node.js的Web開發架構, 使用它可以快速地搭建網站原型,它是一個node.js模組,採用npm全域模組進行安裝。
安裝命令如下:
npm install -g express
安裝完成後,在工作目錄建立一個新項目,假定叫 helloword。
express helloword
此時,會在工作目錄下產生一個helloword 子目錄,如下:
blwang@blwang-desktop:~/workspace/nodejs_workspace$ express helloword create : helloword create : helloword/package.json create : helloword/app.js create : helloword/public create : helloword/public/javascripts create : helloword/public/images create : helloword/public/stylesheets create : helloword/public/stylesheets/style.css create : helloword/routes create : helloword/routes/index.js create : helloword/routes/user.js create : helloword/views create : helloword/views/layout.jade create : helloword/views/index.jade install dependencies: $ cd helloword && npm install run the app: $ node app
根據提示,安裝dependencies, 然後運行node app,就可以在本地的3000連接埠看到產生的預設網站架構。
訪問地址:http://127.0.0.1:3000
Step 3 Install MongoDB安裝參照http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.listsudo apt-get updatesudo apt-get install mongodb-10gen
mongodb 資料庫操作鏈結接如下:http://docs.mongodb.org/manual/core/crud-introduction/
Step4 Install Mongoose
多種中介軟體可以用於串連node.js與MongoDB,目前比較常用的Mongoose。
首先,在之前利用express建立的helloworld項目目錄安裝Mongoose,命令如下:
npm install mongoose --save
然後,就可以在node.js指令碼中串連MongoDB資料庫了。
var mongoose = require('mongoose');mongoose.connect('mongodb://localhost/<資料庫名>');
注意,運行上面這個指令碼時,必須確保MongoDB處於運行中。