• controller/home.js
    1. const {Controller}=require("egg")
    2. const fs=require("fs")
    3. const path=require("path")
    4. class HomeController extends Controller{
    5. async api(){
    6. let {ctx}=this
    7. let list=await ctx.service.home.list()
    8. let filePath=path.join(__dirname,'../public/data.json')
    9. fs.writeFileSync(filePath,JSON.stringify(list))
    10. ctx.body={code:1,data:list}
    11. }
    12. }
    13. module.exports =HomeController
    • service/home.js
    1. const cheerio = require("cheerio")
    2. const { Service } = require("egg")
    3. const superagent = require("superagent")
    4. class HomeService extends Service {
    5. async list() {
    6. return new Promise((resolve, reject) => {
    7. superagent.get("https://cnodejs.org").end((err,res) => {
    8. const $ = cheerio.load(res.text)
    9. let list = [];
    10. $('.cell').map((item, index) => {
    11. list.push({
    12. author: $(index).find('.pull-left').attr('href').slice(6),
    13. title: $(index).find('.topic_title').text().replace(/\n/, '').trim(),
    14. href: $(index).find('.pull-right').attr('href') || ''
    15. })
    16. })
    17. resolve(list)
    18. })
    19. })
    20. }
    21. }
    22. module.exports = HomeService

    -得到数据

    1. [
    2. {
    3. "author": "atian25",
    4. "title": "Node 12 值得关注的新特性",
    5. "href": "/topic/5cbfd9aca86ae80ce64b3175#5d544129697873456c6bd629"
    6. },
    7. {
    8. "author": "alsotang",
    9. "title": "服务器迁移至 aws 日本机房",
    10. "href": "/topic/5bd4772a14e994202cd5bdb7#5d4b976212a0194544415223"
    11. },
    12. {
    13. "author": "daGaiGuanYu",
    14. "title": "typescript 中修改 Date 的 prototype,添加了 export 语句后出现了问题。",
    15. "href": "/topic/5d51302d12a0194544416048#5d56221212a01945444171d7"
    16. },
    17. {
    18. "author": "zilin9980",
    19. "title": "个人网站实现收款的几种方式",
    20. "href": "/topic/5d36c34effed731686461c92#5d5614d912a019454441719a"
    21. }
    22. ]