zoukankan      html  css  js  c++  java
  • 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/");
  • 相关阅读:
    jquery实现回车键执行ajax
    php post请求
    题解 P2825 【[HEOI2016/TJOI2016]游戏】
    莫队
    一些关于数学的知识(总结)
    P3232[HNOI2013]游走
    万物生长 / Tribles
    [BZOJ4244]邮戳拉力赛
    P1095 守望者的逃离
    P3953 逛公园
  • 原文地址:https://www.cnblogs.com/koto/p/5664701.html
Copyright © 2011-2022 走看看