-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
84 lines (78 loc) · 2.34 KB
/
app.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const fs = require('fs');
const path = require('path');
const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
const WebHtmlParse = require('./autoFactory/BingTranslator/engine/webHtmlParse');
const parser = new WebHtmlParse();
function CheckChinese(val) {
let reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g');
return reg.test(val);
}
/**
* 获取字典翻译页面
*/
router.get('/api/translate/bing/html', async (ctx) => {
let { q } = ctx.query;
if (!q || typeof q !== 'string') {
ctx.body = '请求参数错误';
return;
}
const config = fs.readFileSync(path.join(__dirname, './config.json'), {
encoding: 'utf-8'
});
try {
let htmlString = fs.readFileSync(path.join(__dirname, './autoFactory/BingHtml/translate/', q + '.html'), { encoding: 'utf-8' });
ctx.body = htmlString;
} catch (error) {
const url = `https://cn.bing.com/dict/search?q=${CheckChinese(q) ? encodeURI(q) : q}&cc=${config.cc}&form=${config.from}`;
return parser.parse(url).then(
(res) => {
// console.log(res);
console.log('爬虫成功');
ctx.body = res;
},
(err) => {
console.log(err);
ctx.body = err;
}
);
}
});
/**
* 获取json格式的内容
*/
router.get('/api/translate/bing/json', async (ctx) => {
let { q } = ctx.query;
if (!q || typeof q !== 'string') {
ctx.body = '请求参数错误';
return;
}
const config = fs.readFileSync(path.join(__dirname, './config.json'), {
encoding: 'utf-8'
});
try {
let jsonString = fs.readFileSync(path.join(__dirname, './autoFactory/BingHtml/json/', q + '.json'), { encoding: 'utf-8' });
ctx.body = jsonString;
} catch (error) {
const url = `https://cn.bing.com/dict/search?q=${CheckChinese(q) ? encodeURI(q) : q}&cc=${config.cc}&form=${config.from}`;
return parser.parse(url).then(
(res) => {
console.log(res);
console.log('爬虫成功');
let jsonString = fs.readFileSync(path.join(__dirname, './autoFactory/BingHtml/json/', q + '.json'), { encoding: 'utf-8' });
ctx.body = jsonString;
},
(err) => {
console.log(err);
ctx.body = err;
}
);
}
});
app.use(router.allowedMethods());
app.use(router.routes());
app.listen(9000, () => {
console.log('启动成功');
console.log(`http://localhost:9000`);
});