-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
67 lines (49 loc) · 1.44 KB
/
index.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const http = require("http");
const { URL } = require('url');
const path = require("path");
const fs = require("fs");
const axios = require('axios')
const websiteUrl = 'https://baidu.com'
//启动http服务器
http.createServer(onRequest).listen(8888);
console.log("Server has started on 8888.");
//监听请求
function onRequest(request, response) {
var urlObj = new URL(request.url, `http://${request.headers.host}`);
var pathname = urlObj.pathname;
if(pathname.endsWith('/')) pathname += 'index.html'
//保存文件地址
pathname = './download' + pathname
console.log('visit-->', pathname)
if(!fs.existsSync(pathname)){
//请求
axios.get(websiteUrl + request.url, {responseType: 'arraybuffer',})
.then((res)=>{
console.info('write-->', pathname)
//创建文件夹
let dir = path.dirname(pathname)
mkdirsSync(dir)
let fd = fs.openSync(pathname, 'a')
fs.writeSync(fd, res.data)
fs.closeSync(fd)
//响应请求
response.write(res.data)
response.end()
})
.catch((err)=>{
console.error(err)
})
}else{
let data = fs.readFileSync(pathname)
response.write(data)
response.end()
}
}
// 递归创建目录 同步方法
function mkdirsSync(dirname) {
if (fs.existsSync(dirname)) {
return true;
} else {
fs.mkdirSync(dirname, { recursive: true })
}
}