import * as https from 'https';
import * as querystring from 'querystring';
//alt+Enter自动匹配,MD5用的就是require
import md5 = require('md5');
import {appId, appSecret} from './private';
type ErrorMap = {
[key: string]: string
}
//表驱动
const errorMap: ErrorMap = {
52003: '用户认证失败',
52004: 'error2',
'unknown': '服务器繁忙'
}
export const translate = (word: string) => {
console.log(word)
const salt = Math.random()
const sign = md5(appId + word + salt + appSecret)
let from, to
if (/[a-zA-Z]/.test(word[0])) {
//英译中
from = 'en'
to = 'zh'
} else {
//中译英
from = 'zh'
to = 'en'
}
const query: string = querystring.stringify({
q: word,
appid: appId,
from,
to,
salt,
sign
})
const options = {
hostname: 'api.fanyi.baidu.com',
port: 443,
path: '/api/trans/vip/translate?' + query,
method: 'GET'
};
const request = https.request(options, (response) => {
let chunks: Buffer[] = []
//data事件:当流将数据块传送给消费者后触发
response.on('data', (chunk) => {
chunks.push(chunk)
});
//end事件:当流中没有数据可供消费时触发
response.on('end', () => {
//Buffer.concat方法将一组Buffer对象合并为一个Buffer对象
const string = Buffer.concat(chunks).toString()
type BaiduResult = {
error_code?: string,
error_msg?: string
from: string,
to: string,
trans_result: {
src: string,
dst: string
}[]
}
const object: BaiduResult = JSON.parse(string)
if (object.error_code) {
console.error(errorMap[object.error_code] || object.error_msg)
process.exit(2)
}
else {
object.trans_result.map(obj => {
console.log(obj.dst)
})
process.exit(0)
}
})
});
//如果在请求期间遇到任何错误, 则会在返回的请求对象上触发 'error' 事件
request.on('error', (e) => {
console.error(e);
});
//必须始终调用 request.end() 来表示请求的结束
request.end();
}
cli.ts
#!/usr/bin/env node
"use strict"
import * as commander from 'commander';
import {translate} from './main';
const program = new commander.Command()
program
.version('0.0.1')
.name('fy')
.usage('<English>')
.arguments('<English>')
.action(function (English) {
translate(English)
})
program.parse(process.argv)