后端资源精选程序员首页投稿(暂停使用,暂停投稿)

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

2016-03-09  本文已影响1496人  转角遇见一直熊

自从有了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文档。

上一篇 下一篇

猜你喜欢

热点阅读