Node.js介绍1-事件驱动非阻塞

自从有了Node.js,JavaScript也可以在服务器跑了,呵呵呵,代码都是异步,实时高性能,爽的很,写个文章介绍一下Node.js的知识。

什么是Node.js

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。Allows you to build scalable network applications using JavaScript on the server-side.

node.js

可以用Node.js干什么

  1. Websocket Server:聊天室之类
  2. Fast File Upload Client:文件上传服务
  3. Ad Server:广告服务器
  4. 实时数据相关的应用,类似1

Node.js不是啥

  1. web框架:express是一个基于node.js的框架
  2. 应用层: node.js非常底层,直接开发应用应该基于其他库或者框架
  3. 多线程:node.js是单线程的(对于在上面跑的JavaScript应用程序来说)

非阻塞式 I/O 的模型

Node.js可以写出非阻塞的代码

  • 阻塞的代码
var contents = fs.readFileSync('/etc/hosts');
console.log(contents);
console.log('Doing something else');
  • 非阻塞的代码
fs.readFile('/etc/hosts', function(err, contents) { 
    console.log(contents);
});
console.log('Doing something else');

非阻塞代码是有一个回调函数。contents在回调函数中才能拿到,但是console.log('Doing something else');不需要等到读文件结束就可以打印了,这就是非阻塞式 I/O 的模型。

事件驱动

通过一个例子来说明事件驱动

hello world

var http = require('http');
http.createServer(function(request, response) {
    response.writeHead(200);
    response.write("Hello, world.");
    response.end();
}).listen(8080, function() {
    console.log('Listening on port 8080...');
});

上面的例子创建了一个http服务器,返回helloworld问候。测试一下例子。

node hello.js 运行上面的js
curl http://localhost:8080 访问服务

curl命令说明
这个例子可以看出node.js是以事件驱动的。看一下代码中的回调是如何发生的。

事件循环

在上图中,我们看到事件循环不断检查事件,当发现有一个事件发生时,就调用回调函数。
为了加深理解,我们深入到node.js核心去看看
node.js核心

  1. V8引擎解析JavaScript脚本。
  2. 解析后的代码,调用Node API。
  3. libuv库负责Node API的执行。它将不同的任务分配给不同的线程,形成一个Event Loop(事件循环),以异步的方式将任务的执行结果返回给V8引擎。
  4. V8引擎再将结果返回给用户。

我们可以看到node.js的核心实际上是libuv这个库。这个库是c写的,它可以使用多线程技术,而我们的Javascript应用是单线程的。

Node.js中的事件

所有事件的发生和这个类有关EventEmitter

event

我们看一个EventEmitter的代码。

const myEmitter = new MyEmitter();
// Only do this once so we don't loop forever
myEmitter.once('newListener', (event, listener) => {
  if (event === 'event') {
    // Insert a new listener in front
    myEmitter.on('event', () => {
      console.log('B');
    });
  }
});
myEmitter.on('event', () => {
  console.log('A');
});
myEmitter.emit('event');
  // Prints:
  //   B
  //   A

emit可以发出事件,on可以监听事件。
我们再仔细分析一下helloworld.js的代码:

  1. http.createServer的含义

http.createServer([requestListener])#
Returns a new instance of http.Server
.

The requestListener is a function which is automatically added to the 'request' event.

  1. http.Server是啥

Class: http.Server#
This class inherits from net.Server
and has the following additional events:(省略events,可以点击链接自行查看)

  1. net.Server是啥

Class: net.Server#

This class is used to create a TCP or local server.
net.Server is an EventEmitter with the following events:(省略events,可以点击链接自行查看)

好,我们知道EventEmitter是事件的基类,也知道了如何查看node.js文档。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • topics: 1.The Node.js philosophy 2.The reactor pattern 3....
    宫若石阅读 4,798评论 0 1
  • 总结一: [node.js总结](http://www.cnblogs.com/Darren_code/archi...
    xiumeiii阅读 5,918评论 0 14
  • # 模块机制 node采用模块化结构,按照CommonJS规范定义和使用模块,模块与文件是一一对应关系,即加载一个...
    RichRand阅读 7,294评论 0 3
  • Node.js是目前非常火热的技术,但是它的诞生经历却很奇特。 众所周知,在Netscape设计出JavaScri...
    w_zhuan阅读 8,955评论 2 41
  • 一夜萧风花醉舞残红落尽逐水流执笔润墨赋若诗再度绽放待几时
    娟好_静秀阅读 1,690评论 0 1