Node.js入门(下)

Stream
const fs = require('fs')
//读取流
const rs = fs.createReadStream('./01.png')
//写入流
const ws = fs.createWriteStream('./02.png')
//把读取和写入对接 目的是复制01的图片 取名为02
rs.pipe(ws)
http web服务模块

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>Hello Node</h1>
    <img src="01.png" alt=""/>
</body>
</html>

api.js


//文件读取
const fs = require('fs')

// http:用于创建web服务的模块
//创建一个http服务器
const http = require('http')
//读取文件服务器
const server = http.createServer((request,response)=>{
    //打印原型链  request和response都是steam
    // console.log('request',getPrototypeChain(request));
    // console.log('response',getPrototypeChain(response));
    const {url,method,headers} = request
    //是首页并且是get请求
    if(url === '/' && method === 'GET'){
        //读取html 首页
        fs.readFile('index.html',(err,data) => {
            if(err){
                //设置一组
                response.writeHead(500,{
                    'Content-Type':'text/plain;charset=utf-8'
                })
                response.end('服务器错误')
            }
            response.statusCode = 200
            //设置一个
            response.setHeader('Content-Type','text/html')
            response.end(data)
        })
    }else if(url === '/users' && method === 'GET'){
        //读取/users json
        response.writeHead(200,{
            'Content-Type':'application/json'
        })
        response.end(JSON.stringify([{name: 'laowang'}]))
    }else if(method === 'GET' && headers.accept.indexOf('image/*') !== -1){
        //读取图片
        fs.createReadStream('.'+url).pipe(response)
    }else{
        //找不到页面
        response.statusCode = 404
        response.setHeader('Content-Type','text/plain;charset=utf-8')
        response.end('404页面没有找到')
    }
    // response.end('a response')
})

server.listen(3000);
//node api.js运行完毕 在浏览器输入http://localhost:3000/ 查看

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 3,064评论 1 3
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,374评论 0 3
  • 1-------- 走进前端 2-------- jQuery 3-------- CSS 4-------- A...
    依依玖玥阅读 2,368评论 0 34
  • Node.js Node.js 就是运行在服务端的 JavaScript。 Node.js 是一个基于Chrome...
    Gukson666阅读 701评论 0 1
  • 最近在做公司的聊天项目,项目中涉及到了对自己的联系人进行排序的功能,在网上查了下,大多说到了用苹果自带的UILoc...
    himyfairy阅读 1,489评论 1 2