使用 Node.js https 模块做一个命令行翻译工具

305 阅读1分钟

工具介绍:

  • 可在命令行使用 fanyi 命令,进行中英互译
  • 安装:npm i node-fanyi-dongyarn add node-fanyi-dong
  • 使用:fanyi applefanyi 苹果
  • 主要使用了 https 模块的 request 方法,请求百度翻译的 API 完整代码:Gitee | GitHub

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);
}

image.png

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
  });
}