Node command line tool

Project address project source code at the end

See article from 1 to Perfect to write a command line tool with Node

NPM packages involved

  • Chalk (color command line characters)
  • Cheerio (parsing DOM)
  • Is-Chinese
  • No-case (converted to a lowercase string with Spaces between words)
  • Ora (command line loading icon)
  • Request (Node sends request requests)
  • Urlencode (urL-encode strings)

1. Advance summary

The main field specifies the import/export file in package.json, or the bin field if the command line tool is installed.

Configuration commands:

  1. The command name is TRAN, which is the same as the package name
{
  "name": "tran"."bin": "index.js"
}
Copy the code
  1. Or specify a separate command name
{
  "name": "tran"."bin": {
    "yd": "index.js"}}Copy the code

Then write at the beginning of the index.js file

#! /usr/bin/env node // lets the system dynamically find node to execute your script file.Copy the code

Then install the above packages and start writing!

2. Write the code

Obtain the command line input 😁

This can be obtained with process.argv

The process.argv property returns an array containing the command line arguments passed in when the Node.js process is started. The first element is process.execPath. The second element is the path of the JavaScript file being executed. The remaining elements are any additional command-line arguments.

At the beginning of the file, introduce related packages

const chalk = require('chalk')
const ora = require('ora')
const request = require('request')
const isChinese = require('is-chinese')
const urlencode = require('urlencode')
const noCase = require('no-case')
const cheerio = require('cheerio')

const spinner = ora('Loading... ') // Define a copy, equivalent to loading
Copy the code

const word = process.argv.slice(2).join(' ') // Get command line input parameters

Copy the code

After the parameter is obtained, a judgment is made. If the parameter is empty, the execution will not continue. At this time, the process is stopped

if(! word) { spinner.fail(chalk.red('Please enter text')) // This step displays an error, equivalent to loading failure
  process.exit() // Stop the process
}

word = noCase.noCase(word) // Convert words to ones with Spaces in between

Copy the code

Configure the request

const isCh = isChinese(word)
Copy the code

Check if it is Chinese, return true if it is Chinese

const url = () = > {
  return isCh ? 'https://dict.youdao.com/w/eng/' : 'https://dict.youdao.com/w/'
}
Copy the code

The first address is chinese-english translation, the second address is 6.The Chinese or English judgment switch address

const option = {
  url: url() + urlencode(word), //
}
Copy the code

Configure the request address and link Word to the URL

Parsing HTML

request(option.url, (error, response, body) = >{... }})Copy the code

Using Request to send a request, the next step is the Cheerio package, which can be used on the server to parse HTML


 const $ = cheerio.load(body) / / load the HTML
    let result = $('#phrsListTab > .trans-container > ul') // Start looking for the associated ID,class, and tag
      .text() The // text() method converts this to a string
      .replace(/\s+/g.' ') // Use the re to dispose of whitespace

    if(! result) {// Some cases are long sentence translation, there will be no above node, so need to judge
      result = $(
        '#ydTrans > #fanyiToggle > .trans-container > p:nth-child(2)'
      ).text()
      // get the long sentence translation node
    }
    console.log(chalk.green(result))
Copy the code

Run locally

npm link
Copy the code

After executing the command, you can input 😁 with YD plus words

My bin field

  "bin": {
    "yd": "index.js"
  },
Copy the code

Source code attached: index.js

#! /usr/bin/env node

const chalk = require('chalk')
const ora = require('ora')
const request = require('request')
const isChinese = require('is-chinese')
const urlencode = require('urlencode')
const noCase = require('no-case')
const cheerio = require('cheerio')

const spinner = ora('Loading... ')

let word = process.argv.slice(2).join(' ') // Get command line input parameters

word = noCase.noCase(word)

if(! word) { spinner.fail(chalk.red('Please enter text'))
  process.exit() // Stop the process
}
console.log(word)

const isCh = isChinese(word)
const url = () = > {
  return isCh ? 'https://dict.youdao.com/w/eng/' : 'https://dict.youdao.com/w/'
}

const option = {
  url: url() + urlencode(word),
}

spinner.start()

request(option.url, (error, response, body) = > {
  if (error) {
    spinner.fail(chalk.red('ERROR'))}else {
    spinner.stop()

    const $ = cheerio.load(body)
    let result = $('#phrsListTab > .trans-container > ul')
      .text()
      .replace(/\s+/g.' ')

    if(! result) {// console.log(
      // $('#ydTrans > #fanyiToggle > .trans-container > p:nth-child(2)').text()
      // )
      result = $(
        '#ydTrans > #fanyiToggle > .trans-container > p:nth-child(2)'
      ).text()
    }
    console.log(chalk.green(result))
  }
})

Copy the code