1.Hello World
1.1安裝:nodejs
Mac系統(tǒng)上的安裝:
brew install node
如果報錯
Linking /usr/local/Cellar/node/0.10.32...
Error: Could not symlink include/node/ares.h
/usr/local/include/node is not writable.
則執(zhí)行:
sudo chown -R `whoami` /usr/local/include/node
如果npm安裝不成功
Warning: The post-install step did not complete successfully
You can try again using `brew postinstall node`
執(zhí)行
sudo brew postinstall node
2.模塊(Module)
node包管理npm罪裹,
配置國內npm鏡像:
- 1.通過config命令
npm config set registry https://registry.npm.taobao.org
npm info underscore (如果上面配置正確這個命令會有字符串response)
- 2.命令行指定
npm --registry https://registry.npm.taobao.org
npm info underscore
- 3.編輯~/.npmrc
加入下面內容
registry = https://registry.npm.taobao.org
或者搜索鏡像: https://npm.taobao.org
2.1系統(tǒng)模塊
2.2 第三方模塊
Supervisor 監(jiān)測node程序中的文件饱普,當有文件發(fā)生變化時會重啟服務;
2.3 創(chuàng)建自定義模塊
3.異步
默認是異步状共,每個異步方法都對應的同步方法:
例如:readFile()
的同步方法是readFileSync()
4.事件
引入事件模塊require('events')
創(chuàng)建事件em.on('my-event ',function(data){});
觸發(fā)事件em.emit('my-event');
例如:
var events = require('events');
var em = new events.EventEmitter();
var counter = 0;
//每2秒發(fā)出一個事件
var timer = setInterval(function(){
em.emit('tick');
},2000);
em.on('tick',function(data){
counter++;
console.log(counter % 2 ? 'Tick' : 'Tock');
});
5.子進程
引入chile_process
6.框架Express
sudo npm install -g express-generator
原先的express帶cli, 現(xiàn)在把cli拆成了單獨的express-generator包. 原先的express運行生成的項目是node app.js, 因為httpserver相關代碼都在app.js里, 現(xiàn)在這部分代碼移到了項目目錄的bin/www下面, app.js只保留實現(xiàn)app的邏輯代碼, 你需要去運行那個bin/www套耕。 只是很單純的細化應用和包依賴的版本變更。
安裝express 項目,express 會創(chuàng)建好腳手架
express --css less
安裝依賴
cd . && npm install
啟動app
DEBUG=LearnNodejs:* npm start