-
Notifications
You must be signed in to change notification settings - Fork 0
/
4.1.js
45 lines (41 loc) · 1.38 KB
/
4.1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import fs from 'fs'
import superagent from 'superagent'
import mkdirp from 'mkdirp'
import { urlToFilename } from './utils.js'
import { fileURLToPath } from 'url'
import { dirname } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
export function spider(url, cb) {
const filename = `${__dirname}/${urlToFilename(url)}`
fs.access(filename, err => { // (1)
if (err && err.code === 'ENOENT') {
console.log(`Downloading ${url} into ${filename}`)
superagent.get(url).end((err, res) => { // (2)
if (err) {
cb(err)
} else {
mkdirp(__dirname, err => { // (3)
if (err) {
cb(err)
} else {
fs.writeFile(filename, res.text, err => { // (4)
if (err) {
cb(err)
} else {
cb(null, filename, true)
}
})
}
})
}
})
} else {
cb(null, filename, false)
}
})
}
// (1) 检查这个网址所对应的内容是不是已经下载过了。code 的属性是 ENOENT,意味着文件不存在,可以创建一个新的文件
// (2) 如果找不到这个文件,把 url 所表示的网页下载下来
// (3) 确保响应的目录用来承接下载下来的内容
// (4) 把 HTTP 响应消息的主体内容写入文件系统