Node.js:服务器与数据流

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
'); 
})
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/");
原文地址:https://www.cnblogs.com/koto/p/5664701.html