1. Initialize the project

1.1 Project Environment Configuration

  • Create an empty directorynode_fanyi
  • Initialize theyarn init -y
  • Install ts-node-dev globallyyarn global add ts-node-devThis tool is used to supporttypescriptfornodeThe development of
  • Install typescript globallyyarn global add typescriptSupports TS development for compiling TS into JS for final releasenpm
  • Open with webstorm or vscodenode_fanyi
  • Install the Node declaration fileyarn add --dev @types/node

1.2 Environment Test

  • Create SRC /cli.ts in the node_fanyi directory and write the following code

    console.log("ts-node-dev can run")
    Copy the code
  • Run the ts-node-dev SRC /cli.ts command to display ts-node-dev can run

  • Run the TSC -v command to print the TS version number

2. How do I handle command line parameters

2.1 commander. Js

Com.js, the complete solution to the Node.js command line interface

Use commander. Js for quick command-line tool development

Commander. Js document

yarn add commander
Copy the code

2.2 Usage Overview

Create SRC /cli.js under node_fanyi and introduce Commander

import * as commander from "commander";
const program = new commander.Command();

program
  .version("0.0.1")
  .name("fy")
  .usage("<English>")
  .arguments("<English>")
  .action(function (word) {
    console.log(word);
  });
program.parse(process.argv);

Copy the code
  • Version parameter – Indicates the version number
  • Name parameter – Command to use
  • Usage parameter – Optional/Mandatory parameter name
  • Arguments – Specifies the input arguments after the command is passed
  • Action argument – callback function

Run ts-node-dev SRC /cli. ts-h

The action command is used to get the parameters passed in. The ts-node-dev SRC /cli.ts add command is used to print the parameters passed in

src
main.ts

export const translate = (word: string) => {
    console.log(word)
    // doSomething is used here to translate the incoming word and print it out.Copy the code

SRC /cli.ts introduces the translate function in the action callback

import { translate } from "./main";

program
  .version("0.0.1")
  .name("fy")
  .usage(> "< English | | Chinese")
  .arguments(> "< English | | Chinese")
  .action(function (word) {
    translate(word);
  });
Copy the code

The next step is to write the logic of the translation function

3. Translation

3.1 HTTPS. Request Sends a translation request

Modify the main.js code as follows to test whether https.request can send GET requests

import * as https from "https";

export const translate = (word: string) => {
  const options = {
    hostname: "www.baidu.com",
    port: 443,
    method: "GET"}; const request = https.request(options, (response) => { response.on("data", (chunk: Buffer) => {
      console.log(chunk); 
    });
    response.on("end", () => {
      console.log("end");
    });
  });

  request.on("error", (e) => {
    console.error(e);
  });
  request.end();
};

Copy the code

Run the ts-node-dev SRC /cli.ts add command. If the command is correct, chunk End is displayed

3.2 Acquisition and use of translation API

3.2.1 for

You can use the API of Baidu Translation or Youdao Translation. I chose the API of Baidu Translation. You can choose which one to use.

Baidu Translation Youdao Translation

After logging in to the official website, click the product service, General translation API, click “Use now”, generally use the standard version is enough

Click access documentation, which contains interfaces, input parameters, return values, language list, error codes, and access examples

Be careful not to give away your appID and appSecret

Query parameters

 /** * salt random number * sign how the signature is generated in the document appSecret can be seen in the developer info ** use queryString.stringify () to concatenate these query parameters into a string * appId can be seen in the developer info */    
  const salt = Math.random();
  const sign = md5(appId + word + salt + appSecret);
  const query = querystring.stringify({
    q: word, // The word to query
    appid: appId,
    salt,  / / random number
    sign, // Generated signature
    from:"en".// The input language
    to:"zh".// The output language
  });
Copy the code

Interfaces in the interface documentation

  const options = {
    hostname: "api.fanyi.baidu.com",
    port: 443,
    path: "/api/trans/vip/translate?"+ query, // query is the query method generated by the above training parameters:"GET"};Copy the code

3.2.2 use the API

New SRC /private.ts writes the code and adds the file to.gitignore

export const appId = ""; // The appID you applied for
export const appSecret = ""; // The appSecret you applied for
Copy the code

Ts install MD5 and its declaration file yarn add md5 yarn add — dev@types /md5

Main.ts complete code command line translation source code

import * as https from "https";
import * as querystring from "querystring";
import { appId, appSecret } from "./private";
import md5 from "md5";

type ErrorMap = {
  [key: string] :string;
};
const errorMap: ErrorMap = {
  52003: "User authentication failed".54001: "Signature error".54004: "Insufficient account balance"};typeBaiduResult = { error_code? :string; error_msg? :string;
  from: string;
  to: string;
  trans_result: { src: string; dst: string} []; };export const translate = (word: string) = > {
  const salt = Math.random();
  const sign = md5(appId + word + salt + appSecret);
  let from, to;
  // Check whether the input is In Chinese or English
  if (/[a-zA-Z]/.test(word[0]) {from = "en";
    to = "zh";
  } else {
    from = "zh";
    to = "en";
  }
  const query = querystring.stringify({
    q: word,
    appid: appId,
    salt,
    sign,
    from,
    to,
  });

  const options = {
    hostname: "api.fanyi.baidu.com",
    port: 443,
    path: "/api/trans/vip/translate?" + query,
    method: "GET"};const request = https.request(options, (response) = > {
    // Listen for data events and put any returned values in chunks
    let chunks: Buffer[] = [];
    response.on("data".(chunk: Buffer) = > {
      chunks.push(chunk);
    });
    // After end, convert the chunks to the familiar object
    // Then parse the object to determine success or failure
    // Failed to print errMsg
    // Success prints the translated result on the command line
    response.on("end".(a)= > {
      const string = Buffer.concat(chunks).toString();
      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); }}); }); request.on("error".(e) = > {
    console.error(e);
  });
  request.end();
};
Copy the code

Run ts-node-dev SRC /cli.ts add

Ts - node - dev SRC/cli. Ts success

The sample is as follows

That’s basically the end of it, if you want to post to NPM, go ahead

4. Publish to NPM

4.1 registered NPM

Register yourself on the NPM website

4.2 Converting TS to JS

  • Command line operationtsc -- initgeneratetsconfig.jsonfile
  • Modify “outDir” in tsconfig.json file: “dist/” // TSC compilation ts js folder
  • runtscGenerate dist directory and JS file corresponding to TS file
  • willdist/private.jsTo join the.gitignore

4.3 modify the package. The json

The final code is in the final source link

{
  "name": "node_fanyi"// The name of your NPM package may appear as the same as that of someone else's package"version": "0.0.1"// The version of your package should be changed every time it is released"main": "dist/main.js"// Load the entry file"bin"{// Specify the location of the executable file corresponding to each internal command"fy": "dist/cli.js"// the default command is fy},"files": [// The file to upload"dist/**/*.js"],}Copy the code

4.4 Generate code and publish it

    1. runtscRun it before every releasetscTo regenerate thedist
    1. NPM is changed to official source, unofficial source can not publish in order to runnpm install nrm -g nrm use npm
    1. runnpm adduserLog in to NPM and fill in “Username Password email” as prompted.
    1. runnpm publishPost code

5. Possible problems and other tips

  1. You’ve never used TS?

    Change the ts suffix to js, remove the declaration

  2. Code error?

    Copy the source code into your code and see if it works

  3. Unsuccessful launch?

    No official source

    Version Does not change the version number

    Name is the same as someone else’s published name

  4. The other?

    I don’t know… Let me know if you have any further questions

6. Security issues and more

  1. Don’t expose your AppID and appSecret or someone else can use your appID and appSecret for something else. Try to only open the standard version

  2. Currently only simple single word and Chinese sentence translation, it may be added later…

  3. Experience the command line translation tool I have published. If it doesn’t work, I have disabled my Baidu Translation API service

npm install fanyi-f -g 
Copy the code
fy add
Copy the code

7. The source code

Command line translation source code

Afterword.

The article is a personal summary, the inadequacy also please leave a message or private letter.

Please indicate the source of reprint.

The above.