初识Node

Node的定义:一个搭建在Chrome JavaScript运行时上的平台,用于构建高速、可伸缩的网络程序。

 
Node构建与JS之上,在服务器端,Node使用V8虚拟机,执行的是本地机器码,省去了编译和解释的过程,速度更快。
 
Node为服务端JS提供了一个事件驱动(事件轮询)的、异步(非阻塞IO)的平台。能够响应更多的请求。
 
Node针对的是数据密集型实时(DIRT)程序,目标是依靠自身轻量的IO处理模型,保证响应能力,实现和浏览器一样的实时响应效果。
 
Node提供了适用各种WIndows和UNIX系统的DIRT方式,底层的IO库屏蔽了宿主操作系统的差异性,程序可以在多个设备上移植和运行。
 
示例程序:
1、读取系统文件
var fs = require('fs');
fs.readFile('./resource.json', function (err, data) {
   console.log(data)
})
 
2、响应HTTP请求
var http = require('http');
http.createServer(fuction (request, response) {
   response.writeHead(200, {'Content-Type': 'text/plain'});
   response.end('Hello World ');
}).listen(3000);
console.log('Server running at http://localhost:3000/');
 
这是另一种写法
var http = require('http');
var server=http.createServer();
server.on('request', fuction (request, response) {
   response.writeHead(200, {'Content-Type': 'text/plain'});
   response.end('Hello World ');
});
server.listen(3000);
console.log('Server running at http://localhost:3000/');
 
3、异步处理读取的数据流
var fs = require('fs');
var stream = fs.createReadStream('./resource.json');
stream.on('data', function(chunk) {
  console.log(chunk);
});
steram.on('end', function() {
  console.log('finished');
});
 
4、向客户端返回图片
var http = require('http');
var fs = require('fs');
http.createServer(fuction (request, response) {
   response.writeHead(200, {'Content-Type': 'image/png'});
   fs.createReadStream('./image.png').pipe(response);
}).listen(3000);
console.log('Server running at http://localhost:3000/');
 
原文地址:https://www.cnblogs.com/lianjinzhe/p/13411257.html