NodeJS(1)

1、综述
1.1
 

Node.js特性

  • Node.js库的异步和事件驱动的API全部都是异步就是非阻塞。它主要是指基于Node.js的服务器不会等待API返回的数据。服务器移动到下一个API调用,Node.js发生的事件通知机制后有助于服务器获得从之前的API调用的响应。

  • 非常快的内置谷歌Chrome的V8 JavaScript引擎,Node.js库代码执行是非常快的。

  • 单线程但高度可扩展 - Node.js使用具有循环事件单线程模型。事件机制有助于服务器在一个非阻塞的方式响应并使得服务器高度可扩展,而不是创建线程限制来处理请求的传统服务器。Node.js使用单线程的程序,但可以提供比传统的服务器(比如Apache HTTP服务器)的请求服务数量要大得多。

  • 没有缓冲 - Node.js的应用从来不使用缓冲任何数据。这些应用只是输出数据在块中。

  • 许可证协议 - Node.js 在MIT协议 下发布

 
1.2

在哪里可以使用Node.js?

以下是Node.js证明自己完美的技术的合作伙伴的领域。

  • I/O 绑定应用程序

  • 数据流应用

  • 数据密集型实时应用(DIRT)

  • JSON API的应用程序

  • 单页面应用

1.3创建HelloWorld程序

Node.js应用程序由以下三个重要部分组成:

  • 导入所需模块: 使用require指令来加载javascript模块

  • 创建一个服务器: 服务器这将听监听在Apache HTTP服务器客户端的请求。

  • 读取请求并返回响应: 在前面的步骤中创建的服务器将响应读取由客户机发出的HTTP请求(可以是一个浏览器或控制台)并返回响应。

步骤 1:导入所需的包

使用require指令来加载 HTTP 模块。

var http = require("http")

步骤 2:使用http.createServer方法创建HTTP服务器。通过参数函数请求并响应。编写示例实现返回“Hello World”。服务器在8081端口监听。

http.createServer(function (request, response) {
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   // send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);
// console will print the message
console.log('Server running at http://127.0.0.1:8081/');

步骤 3: 创建一个 js 文件在 helloworld.js 在 D:\>yiibai_worksp.

File: helloworld.js

var http = require("http")
http.createServer(function (request, response) {  
   response.writeHead(200, {'Content-Type': 'text/plain'});  
   response.end('Hello World\n');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');

现在运行 helloworld.js 看到结果:

D:\yiibai_worksp\nodejs>node helloworld.js

验证输出,服务器应用已经启动!

Server running at http://127.0.0.1:8081/
2、标准模块
使用node中附带的模块,这些模块都被编译进了node二进制文件中。
使用模块的方法:调用“require('name')”并将返回值赋给一个和模块同名的局部变量。例如:
 
var sys = require('sys');
 
3、Buffers缓存对象
 
Buffer对象是全局变量,与JavaScript中的String对象之间的转换需要指定编码方式:
 
'ascii' - 应用于7位ASCII数据
'utf8' - Unicode字符
'binary'-已被淘汰
 
初始化:
new Buffer(size) - 创建指定
new Buffer(array) 从数组新建buffer对象
new Buffer
new Buffer(str,encoding = 'utf8')
 
若不指定,编译报错。
 
 
4、EventEmitter事件触发器
Node中很多对象都会触发事件,所有能够触发事件的对象都是events.EventEmitter的实例。
 
function(event,listener){}
 
5、Streams 流
Stream是一个抽象接口,分为可读流与可写流。

猜你喜欢

转载自www.cnblogs.com/ygria/p/9540196.html