This is the first day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Introduction:

Hello everyone, I’m Rongding. I don’t know if you need to often look up words and some long and short sentences when you are developing. Because my English level is not very high, I often use word lookup tools such as Youdao frequently. However, switching back and forth between editor and translation software or other things inevitably affects the efficiency, so I decided to write a translation gadget that can be easily used at the terminal. Here is to share my cli tool making process ~

The project requirements

  1. First of all, it is clear that the purpose of this tool is not to switch back and forth between software.
  2. You can translate from Chinese to English, from English to Chinese, and you can translate not only words but also long and short sentences (we will use the dao API here).
  3. You can pronounce words and long and short sentences.
  4. And it needs to be small enough (my Unpacked Size is only 5.17 KB)

precondition

The node is installed.

Clear logical requirements

  1. Use the Youdao Translation API in Node.js for literal translation. Whether it is translated from Chinese to English or English to Chinese

  2. The Json returned by the API is then formatted and output to the terminal to complete the translation

  3. By adding parameters can achieve translation, reading, help and other functions of free choice

    Command + text# Translate the textCommand + text + -s /--say# will read the text and translate it without argumentsCommand + -h / -help # Terminal output help document
    
    Other functions can be completed by themselves according to specific needs
    Copy the code

Implementation steps

  • After creating a project directory, open the terminal in the current directory

    # Enter the following command
    npm init -y
    Copy the code

  • I’m using vsCode for the editor. Open the project directory in the editor

  • Create a bin folder and create a js file in the bin folder to test the command line tool.

  • Configure the following information in packjson.js: The commands can be customized (ts, aaa, BBB).

  • Then use:

    npm link
    Copy the code

    After the link, we can go throughnpm ls -gCheck whether it is successful (if the current folder is mapped to the global package, link is successful)

    We use the ts command in the terminal, and you can see that the console.log in the JS file that we started to create is executed. So far, our tool is basically finished. The next step is to write the logic

  • In the project, text highlighting, words, etc., command line parameters are obtained mainly by colors,say, and yargs

    So let's install these three dependencies first
    yarn add say colors yargs -S
    Copy the code
  • After the installation, import it to the js file in the bin folder

    const colors = require("colors");
    const say = require("say");
    const argv = require("yargs").argv,
    queryStr = encodeURI(argv.\_.join(""));
    Copy the code
  • The command is processed logically first

    if(! queryStr) {// There are no parameters after the command
        console.log("Here's the help text");
        console.log("Please enter a word or phrase [-s,--say]");
    } else {
        // With arguments --say or -s, play
        if (argv.say == true || argv.S == true) {
            console.log("In play...".rainbow);
            say.speak(queryStr);
            return;
        }
        // Send text to Youdao API for word lookup
        translate(queryStr);
    }
    Copy the code
  • Define the lookup function

    function translate(query) {
        // Send a translation request
        let http = require("http");
        // 1. Options for the request
        let options = {
            host: "fanyi.youdao.com".port: "80".path:
                "/openapi.do? Keyfrom = translation - tool&key = 1730699468 & type = = data&doctype json&version = 1.1 & q =" +
                query,
        };
        // let options = ` http://aidemo.youdao.com/trans?q=${query}&&from=Auto&&to=Auto`;
        // The callback function that handles the response
        let callback = function(response) {
            // Keep the data updated
            response.on("data".function(data) {
                // Format and highlight the returned data
                format(data);
            });
            response.on("end".function() {
                // The data is received
                console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
            });
        };
        // Send the request to the server
        let req = http.request(options, callback);
        req.end();
    }
    Copy the code
  • Defining formatting functions

    function format(json) {
        let data = JSON.parse(json),
            pronTitle = "Pronunciation:",
            pron = data.basic ? data.basic.phonetic : "No",
            mainTitle = "Translation:",
            mainTrans = "",
            webTitle = "Internet definition:",
            machineTrans = "",
            webTrans = "",
            template = "";
        let basic = data.basic,
            web = data.web,
            translation = data.translation;
        if (basic ? basic : "") {
            for (let i = 0; i < basic.explains.length; i++) {
                mainTrans += "\n"+ basic.explains[i]; }}if (web ? web : "") {
            for (let i = 0; i < web.length; i++) {
                webTrans +=
                    "\n" +
                    (i + 1) +
                    ":" +
                    web[i].key.red.bold +
                    "\n" +
                    web[i].value.join(",");
            }
        }
        translation ? (machineTrans = translation) : false;
        template =
            pronTitle.red.bold +
            pron +
            "\n" +
            mainTitle.green.bold +
            mainTrans +
            "\n" +
            webTitle.blue.bold +
            webTrans +
            "\n" +
            "Machine translation:".green.bold +
            machineTrans;
        console.log(template);
    }
    Copy the code
  • Complete code

        #! /usr/bin/env node
    
        const colors = require("colors");
        const say = require("say");
        const argv = require("yargs").argv,
            queryStr = encodeURI(argv._.join(""));
        / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
        if(! queryStr) {// There are no parameters after the command
            console.log("Here's the help text");
            console.log("Please enter a word or phrase [-s,--say]");
        } else {
            // With arguments --say or -s, play
            if (argv.say == true || argv.S == true) {
                console.log("In play...".rainbow);
                say.speak(queryStr);
                return;
            }
            // Send text to Youdao API for word lookup
            translate(queryStr);
        }
        / / format
        function format(json) {
            let data = JSON.parse(json),
                pronTitle = "Pronunciation:",
                pron = data.basic ? data.basic.phonetic : "No",
                mainTitle = "Translation:",
                mainTrans = "",
                webTitle = "Internet definition:",
                machineTrans = "",
                webTrans = "",
                template = "";
            let basic = data.basic,
                web = data.web,
                translation = data.translation;
            if (basic ? basic : "") {
                for (let i = 0; i < basic.explains.length; i++) {
                    mainTrans += "\n"+ basic.explains[i]; }}if (web ? web : "") {
                for (let i = 0; i < web.length; i++) {
                    webTrans +=
                        "\n" +
                        (i + 1) +
                        ":" +
                        web[i].key.red.bold +
                        "\n" +
                        web[i].value.join(",");
                }
            }
            translation ? (machineTrans = translation) : false;
            template =
                pronTitle.red.bold +
                pron +
                "\n" +
                mainTitle.green.bold +
                mainTrans +
                "\n" +
                webTitle.blue.bold +
                webTrans +
                "\n" +
                "Machine translation:".green.bold +
                machineTrans;
            console.log(template);
        }
        // Send the request
        function translate(query) {
            // Send a translation request
            let http = require("http");
            // 1. Options for the request
            let options = {
                host: "fanyi.youdao.com".port: "80".path:
                    "/openapi.do? Keyfrom = translation - tool&key = 1730699468 & type = = data&doctype json&version = 1.1 & q =" +
                    query,
            };
            // let options = ` http://aidemo.youdao.com/trans?q=${query}&&from=Auto&&to=Auto`;
            // The callback function that handles the response
            let callback = function(response) {
                // Keep the data updated
                response.on("data".function(data) {
                    // Format and highlight the returned data
                    format(data);
                });
                response.on("end".function() {
                    // The data is received
                    console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
                });
            };
            // Send the request to the server
            let req = http.request(options, callback);
            req.end();
        }
    Copy the code
  • The basic functions of the translation tool are now complete

Release the CLI tool to NPM

  • First of all, you should have your own account in the npm.js official website. (If you don’t have one, please register one by yourself.)

  • In the current directory terminal run NPM adduser (note: use Taobao source will report an error, to change back), enter NPMJS account password email.

  • Finally, run NPM Publish to publish the code on NPM

  • Check out the code you just released on NPM

  • Here, the tool has been released successfully, we go back to our own project directory, run NPM unlink TS on the terminal to unbind the previous association, and then type TS. At this time, we find that the command has reported an error, indicating that the unbinding is successful, we run NPM I [your package name] -g and enter ts again after the installation is complete We found that it was ready to be translated and read

  • On Linux or MAC, you can install your own translation widget globally using NPM as long as you have installed the Node environment. It can be used in CMD or powerShell.

  • My project code has been uploaded to Github. If you like it, you can click star. Thank you! (Finish ~ scatter flowers)

The last

I am very happy to be strong with you. You can follow my public account, Qianpozhai. Hop over key caps and characters, code and programs with me.Copy the code