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
|
const { zh } = require('./zh.ts'); const http = require('http'); var md5 = require('md5'); const fs = require('fs'); let fanyiData = {}; async function request() { let salt = 1;
for (let i in zh) { const text = zh[i].trim(); const key = i; salt++; const appid = "20191211000365172"; const pwd = "j1pxAoOJn32rRKnwBXxu"; const sign = md5(`${appid}${text}${salt}${pwd}`); console.log('开始翻译---',i); const url = `http://api.fanyi.baidu.com/api/trans/vip/translate?q=${text}&from=zh&to=en&appid=${appid}&salt=${salt}&sign=${sign}`; await new Promise(resolve => { http.get(url, res => { let str = ''; res.on('data', chunk => str += chunk); res.on('end', () => { const json = JSON.parse(str); console.log('翻译完成,返回结果:',json); console.log('################################'); if (json.trans_result) { const curValue = json.trans_result[0].dst; fanyiData[i] = curValue.substring(0,1).toUpperCase()+curValue.substring(1,); }else{ fanyiData[i] = "本次翻译无效!!!!!!!" } setTimeout(()=>{ resolve(json); },1000) })
}) }) } console.log(fanyiData); const fanyiDataTostring =JSON.stringify(fanyiData); const template = `export const en: any = ${fanyiDataTostring}`; console.log(template); fs.writeFile(__dirname+'/en.ts',template,'utf8',err=>{ if(err){ throw err; } console.log('写入到en.ts成功') })
}
request();
|