- controller/home.js
const {Controller}=require("egg")const fs=require("fs")const path=require("path")class HomeController extends Controller{async api(){let {ctx}=thislet list=await ctx.service.home.list()let filePath=path.join(__dirname,'../public/data.json')fs.writeFileSync(filePath,JSON.stringify(list))ctx.body={code:1,data:list}}}module.exports =HomeController
- service/home.js
const cheerio = require("cheerio")const { Service } = require("egg")const superagent = require("superagent")class HomeService extends Service {async list() {return new Promise((resolve, reject) => {superagent.get("https://cnodejs.org").end((err,res) => {const $ = cheerio.load(res.text)let list = [];$('.cell').map((item, index) => {list.push({author: $(index).find('.pull-left').attr('href').slice(6),title: $(index).find('.topic_title').text().replace(/\n/, '').trim(),href: $(index).find('.pull-right').attr('href') || ''})})resolve(list)})})}}module.exports = HomeService
-得到数据
[{"author": "atian25","title": "Node 12 值得关注的新特性","href": "/topic/5cbfd9aca86ae80ce64b3175#5d544129697873456c6bd629"},{"author": "alsotang","title": "服务器迁移至 aws 日本机房","href": "/topic/5bd4772a14e994202cd5bdb7#5d4b976212a0194544415223"},{"author": "daGaiGuanYu","title": "typescript 中修改 Date 的 prototype,添加了 export 语句后出现了问题。","href": "/topic/5d51302d12a0194544416048#5d56221212a01945444171d7"},{"author": "zilin9980","title": "个人网站实现收款的几种方式","href": "/topic/5d36c34effed731686461c92#5d5614d912a019454441719a"}]
