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/");
  • 相关阅读:
    转:python2.x 和 python3.x的区别
    迭代器
    C++学习笔记-预备知识
    phpstudy扩展mongoDB
    Linux gd库安装步骤说明
    Linux jpeglib库的安装
    github开源项目
    本地文件拖拽到虚拟机里,文件存储位置
    linux php 扩展安装
    CentOS6.10 Nginx无法解析php文件
  • 原文地址:https://www.cnblogs.com/koto/p/5664701.html
Copyright © 2011-2022 走看看