请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

写入数据的时候报‘no such file or directory’

`import * as superagent from ‘superagent’
import * as cheerio from ‘cheerio’
import * as path from ‘path’
import * as fs from ‘fs’
interface Course {
title: string,
count: number
}
interface CourserResult {
time: number,
data: Course[]
}
interface Content {
[propName: number]: Course[]
}
class Crowller {
private secret = ‘secretKey’
private url = ’http://www.dell-lee.com/typescript/demo.html?secret=${this.secret}‘
private getCouseInfo (html: string) {
const $ = cheerio.load(html)
const couseItem = $(’.course-item’)
let courseInfos: Course[] = []
couseItem.map((index, element) => {
const descs = $(element).find(’.course-desc’)
const title: string = descs.eq(0).text()
const count: number = +descs.eq(1).text().split(’:’)[1]
courseInfos = […courseInfos, {
title,
count
}]
})
return {
time: (new Date()).getTime(),
data: courseInfos
}
}
private async getRawHtml() {
const res = await superagent.get(this.url)
return res.text
}
private generateJsonContent (courseInfo: CourserResult) {
const filePath: string = path.resolve(__dirname, ‘…/data/course.json’)
let fileContent: Content = {}
if (fs.existsSync(filePath)) {
fileContent = JSON.parse(fs.readFileSync(filePath, ‘utf-8’))
}
fileContent[courseInfo.time] = courseInfo.data
console.log(fileContent)
fs.writeFileSync(filePath, fileContent, ‘utf-8’)
}
private async initSpiderProcess () {
const html: string = await this.getRawHtml()
const courseInfo: CourserResult = await this.getCouseInfo(html)
this.generateJsonContent(courseInfo)
}
constructor () {
this.initSpiderProcess()
}
}

const crowller = new Crowller()`

图片描述

正在回答

2回答

写入或者创建文件没有权限,你可以自己倒目录下先自己创建一个course.json文件

0 回复 有任何疑惑可以回复我~
GoBig_or_GoHome 2021-09-08 06:22:51

这里我也遇到了完全相同的报错 no such file or directory, open! 因为Dell老师讲课时默认创建了data文件夹.而我们自己会忘记创建data文件夹. 若创建了与src平级的data文件夹,course.json文件就会在第一次运行代码时,自动创建出来. 

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信