用Node.JS 实现翻译功能

main.ts

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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值