Node.js 學習日記--我們一起來讀文檔~

爲啥會寫這個呢,因爲我懶得把他們寫在本子上。

之前照着Node.js上的教程做了一個網站並且發佈在了heroku網站上,想仔細看看Node.js到底還能做些啥,所以開始看文檔,希望能對自己和你們有幫助。


Synopsis

以下是文檔中第一個例子,一般都是弄個簡單的,讓你一看,哎呀,這麼簡單啊,然後就去試一試了。

var http =require('http');


http.createServer(function(request, response){  response.writeHead(200,{'Content-Type':'text/plain'});

response.end('Hello World\n');}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');


只要你安裝了Node.js 在CMD中執行下面的代碼,然後去 localhost:8124/

就可以看到效果了,你隨便看上面的代碼就知道打印一個Hello World出來。

> node example.jsServer running at http://127.0.0.1:8124/


接下來就是

Global Objects

These objects are available in all modules. Some of these objects aren't actually in the global scope but in the module scope - this will be noted.


說以下的這些都是全局變量,你在所有的模型中都能用到,但是在某些模型的範圍內又不能用,我的天!

global

In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

這段話我只看到我在模型中定義的全局變量只針對自己這個類有用,其他我都沒看到。

process

這個模型是emmiter的一個實例。emmiter是Node.js中用來發送/處理消息的,感覺很像java中的handler,比handler爽的是,你不用考慮UI線程什麼的,哦也!

雖然是要看process,但是不看看他爸爸emmiter是做什麼的可不行,所以還是要說emmiter能做什麼吧。


Class: events.EventEmitter

To access the EventEmitter class, require('events').EventEmitter.

All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when a listener is removed.

比較在意這一句話,你添加一個新的listener的時候,別的listener會收到事件,這個是爲啥呢?能用來做什麼呢?防小三?

總之,emitter可以收發事件,查看事件的監聽者們。


回頭看process!

Event: 'exit'

Emitted when the process is about to exit. This is a good hook to perform constant time checks of the module's state (like for unit tests). The main event loop will no longer be run after the 'exit' callback finishes, so timers may not be scheduled.

Example of listening for exit:

process.on('exit',function(){

setTimeout(function({

console.log('This will not run');}

       ,0);

console.log('About to exit.');}

);


當收到exit這個消息後,主循環就停止了,不會再處理信息了,所以那個timeout裏面的函數邊不會觸發了。


Event: 'uncaughtException'

當收到沒有處理的exception的時候會跑到這裏,文檔說這個方法粗糙至極,要考慮刪掉,所以還是別看了。他建議使用domain。在domain中有這樣一句話。

By the very nature of how throw works in JavaScript, there is almost never any way to safely "pick up where you left off", without leaking references, or creating some other sort of undefined brittle state.

JavaScript中沒有安全的錯誤處理麼?


現在又要去看domain了。


吃飯去咯



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章