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了。


吃饭去咯



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