码迷,mamicode.com
首页 > Web开发 > 详细

node.js服务器与数据流

时间:2016-07-12 21:21:28      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

1.Node 常被用来构建服务器,下面代码就是创建了一个服务器。

var http = require(‘http‘);
var server = http.createServer();
server.on(‘require‘,function(req,res){
    res.writeHead(200,{‘Content-Type‘:‘text/plain‘});
    res.end(‘Hello,World\n‘); 
})
server.listen(3000);
console.log(‘Server running at http://localhost:3000/‘);

主要使用createServer()方法。

 

2.Node在数据流和数据流动上也很强大。通过将数据一块一块的传送,开发人员可以每收到一块数据就开始处理,而不用等所有数据到了才能处理。下面就是一个用数据流的方式处理json数据的例子:

var stream = fs.createReadStream(‘./resource.json‘)
stream.on(‘data‘,function(chunk){
    console.log(chunk)
})
stream.on("end",function(){
    console.log("finished")
})

 

3.借用一下前面的http服务器,看看一张图片如何流到客户端:

var http = require("http");
var fs = require("fs");
http.createServer(function(req,res){
    res.writeHead(200,{"Content-Type":"image/png"});
    fs.createReadStream("./image.png").pipe(res);
}).listen(3000);
console.log("Server running at http://localhost:3000/");

 

node.js服务器与数据流

标签:

原文地址:http://www.cnblogs.com/koto/p/5664701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!