工具介绍:
1. 安装依赖
yarn add commander@3.0.2
yarn add md5
yarn add @types/md5 -D
yarn add @types/node -D # 安装这个是因为使用了 typescript
2. cli.ts 中调用 main.ts 的方法
// cli.ts
const program = require('commander');
const pkg = require('../package.json');
const { translate } = require('./main');
program
.version(pkg.version)
.name('fy')
.usage('<English>')
.arguments('<English>')
.action(function (english) {
translate(english)
});
program.parse(process.argv);
// main.ts
export const translate = (word: string) => {
console.log('word:', word);
}
3. 调用百度翻译 API 得到翻译结果
这里使用的是百度翻译 API,点击查看百度翻译开放平台文档。
// main.ts
const https = require('https');
const querystring = require('querystring');
const md5 = require('md5');
const { appid, secret } = require('./private');
export const translate = (word: string) => {
const salt = Math.random();
const sign = md5(`${appid}${word}${salt}${secret}`);
const query: string = querystring.stringify({
q: word, from: 'en', to:'zh', appid, salt, sign
});
const options = {
hostname: 'api.fanyi.baidu.com',
port: 443,
path: `/api/trans/vip/translate?${query}`,
method: 'GET'
};
const req = https.request(options, (res) => {
const chunks = [];
res.on('data', chunk => {
chunks.push(chunk)
});
res.on('end', () => {
const content = Buffer.concat(chunks).toString()
const result = JSON.parse(content)
if (result.error_code) {
console.error(result.error_msg)
process.exit(2)
} else {
result.trans_result.map(item => {
console.log(item.dst)
})
process.exit(0)
}
})
});
req.on('error', (e) => {
console.error(e);
});
req.end();
}
4. 中英互译
// main.ts(部分代码)
export const translate = (word: string) => {
let isEnglish = false;
if (/[a-zA-Z]/.test(word[0])) isEnglish = true;
// ...
const query: string = querystring.stringify({
q: word,
from: isEnglish ? 'en' : 'zh',
to: isEnglish ? 'zh' : 'en',
appid, salt, sign
});
}