1.0.3 • Published 1 year ago

translation-for-tool v1.0.3

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

Command line translation.

安装

npm install translation-for-tool -g

# or
npx yarn add translation-for-tool -g

# or
npx pnpm add translation-for-tool -g

使用

t hello world

t 你好,世界

#支持驼峰翻译,在翻译网站是不支持的
t helloWorld

构建命令行工具 - 初始化

// 在命令行中直接运行该脚本
#! /usr/bin/env node

在 package.json 下添加命令

"bin": {
    "translation": "./bin/translation.js"
  },

使用 link 命令,将命令链接到全局,这样就可以直接在命令行中使用该命令了。

npm link

查看是否链接成功

npm list -g 

在终端使用 translation 命令,即可运行该脚本进行测试

命令行中文字高亮,单词等阅读体验优化

pnpm add say colors yargs

colors: 颜色,主要用于文字高亮 say: 语音播报 yargs: 命令行参数解析

node 复制文字剪贴板

const { exec } = require('child_process');
const iconv = require('iconv-lite');
exec('clip').stdin.end(iconv.encode(translation[0], 'gbk'));

最终代码

#! /usr/bin/env node

const colors = require("colors");
const { exec } = require('child_process');
const iconv = require('iconv-lite');
const say = require('say');

const argv = require("yargs").argv

// 获取命令行参数
let commandParams = argv._.join(' ');

if(!commandParams){
    console.log("请输入单词或短句,例如:translation hello world!".red, "或者:translation hello world! --lang en".red);
    console.log('语言参数:en 英语,zh 中文,默认为中文,使用 -S 参数可以朗读,例如:translation hello world! -S'.red);
}else{
    argv['S'] && say.speak(commandParams);

    // ⚡ 转化,无法翻译驼峰
    commandParams = commandParams.replace(/[A-Z]/g,(A_Z) => {
        return ' '+A_Z
    })
    translation(commandParams)
}


function translation(commandParams) {
    console.log(commandParams,'commandParams');
    const http = require("http");
    // 判断是否是中文
    // const isChinese = /[\u4e00-\u9fa5]/.test(commandParams);
    // commandParams = isChinese?encodeURI(commandParams):commandParams;
    const options = {
        host: "fanyi.youdao.com",
        port: "80",
        path:
            `/openapi.do?keyfrom=translation-tool&key=1730699468&type=data&form=auto&to=auto&doctype=json&version=1.1&q=${encodeURI(commandParams)}`,
    };
    const callback = function(res) {
        res.on("data", function(buffer) {
            // bufferToJson 是一个将buffer转换成json的方法
            format(buffer);
        });
        res.on("end", function() {
            // console.log('🎉🎉🎉')
        });
    };
    http.request(options, callback).end()
  
    
}

//  https://www.npmjs.com/package/emojify.js emoji表情
// https://blog.csdn.net/yzpbright/article/details/122886240 命令行读取上一次记录
function format(buffer) {
    const data = JSON.parse(buffer);
    const {translation, basic, web,query} = data;
    console.log(`▶ ${query}`.yellow.bold);
    console.log(`✓ ${translation.join(',')}`.green.bold);
   
    exec('clip').stdin.end(iconv.encode(translation[0], 'gbk'));
}