zoukankan      html  css  js  c++  java
  • day03

     

    复习了nodejs的内容

    整明白了express框架和路由,下面是我自己的总结:

    const http = require("http");
    const fs = require("fs");
    const cheerio = require("cheerio"); //引入服务器版的jquery   
     //console.log(cheerio);
    http.get("http://news.baidu.com",(res)=>{  
        // http发起一个get请求,读取百度新闻里的数据,读取成功后会在这个回调里面拿到百度新闻了
        // res是一个流对象,里面就有所有的数据
        // console.log(res);
        var body = "";   // 把所有数据放在这里
        res.setEncoding("utf-8");
        res.on("data",(thunk)=>{
            body += thunk;
        })
        res.on("end",()=>{  
            // console.log(body);
            // 把得到的数据body写入news2.html文件里
            // fs.writeFileSync("./news.html",body,"utf-8");
            // 或者用创建流的方式写:
            // var ws = fs.createWriteStream("./news2.html");
            // ws.write(body,"utf-8");

            const $ = cheerio.load(body);   //把得到的字符串(数据)转化为一个$(jquery)对象
            // 获取焦点新闻列表元素,并把内容写到文本文件里
            // fs.writeFileSync("./focusnews.txt","","utf-8"); //创建一个文件,不用写
            $(".focuslistnews a").each((index,item)=>{
                fs.appendFileSync("./focusnews.txt",$(item).text()+" ","utf-8"); //  表示各个平台下都能换行
                // item表示每个a标签,$(item).text( )表示a标签的文本
                // console.log($(item).text());
                // console.log(index);
            })
        })
    })
     
    const path = require("path");
    const express = require("express"); //引入express

    const app = express();  //实例化 (创建了一个服务器)
    app.get("/",(req,res)=>{
        res.redirect("./hello");    //重定向:看到/就自动跳转到/hello
    })
    app.get("/hello",(req,res)=>{   
        //(这个服务器能响应用户的请求:当用户发送/hello请求时会执行回调函数)
        if(req.url === "favicon.ico") return;
        res.send("我在这里做一个测试~~");
    })

    app.listen(3001,()=>{   //(在3000端口去监听)
        console.log("listen 3000^……");
    })
  • 相关阅读:
    区间树
    最大流
    单源最短路径
    散列表
    最小生成树
    软件体系结构2
    软件体系结构
    Leetcode 687.最长同值路径
    Leetcode 686.重复叠加字符串匹配
    Python测试框架
  • 原文地址:https://www.cnblogs.com/wufenfen/p/12688478.html
Copyright © 2011-2022 走看看