Project initialization
Yarn init -y // Initialize a package.json fileCopy the code
Create a cli.js for the command line call
console.log('this is cli.js')
Copy the code
Run the Node CLI.
commander
Commander is widely used in command-line development
Comamnder has several commonly used apis
- program.version
Program.version can be the current version that the user knows about, and we can dynamically assign it directly via package.json
const pkg = require('./package.json');
program.version(pkg.version);
Copy the code
- process.argv
Process. argv is an array that can be used to retrieve commands entered by the user
Process.argv. length tells us how many words the user has entered
- program.option
program.option('-x, --xxx', 'wait the x')
Copy the code
Program. option is used for commands that require the user to enter –
- program.command
The program. The command (' clear '). The description (' clear all tasks'). The action (() = > {/ /... });Copy the code
The program.command command is used to set the command that the user does not need to enter “-“. It can process some complex logic.
Imports and exports in Node
Nodejs is different from JS in that it has a special export method
// Exports const obj = {} module.exports = obj // imports const obj = require('... ')Copy the code
Home directory and concatenation path
- Obtaining the home path
const homedir = process.env.HOME || require('os').homedir(); // require(' OS ').homedir() Gets the HOME path of the systemCopy the code
- Stitching path
const p = require('path')
const dbpath = p.join(homedir, '.todo2')
Copy the code
Fs file system
With fs in Node, we can do reads/writes and so on
- fs.readFile
fs.readFile(path, {flag: 'a+'}, (err, data) => {
//xxxxx
})
Copy the code
{flag: ‘a+’} : If no such file exists, create one
- fs.writeFile
fs.writeFile(path, data, (error) => {
//xxxxx
})
Copy the code
Since the above method is an asynchronous operation, we can use Promise to do something with the callback function.
inquirer
Inquirer is a menu-like library on the command line
Note: Choice in inquirer can be an array, object, or function. When it is an object, value should be a string (not a number), otherwise it may be buggy
Published to the NPM
- package.json
- Name must be a unique value
- Bin Issues subsequent commands
- Files Files used by the command line
- The main file entry for the main program
- You need to add shebang to the CLI file
- #! /usr/bin/env node
-
Add executable permissions to the project file by pointing to chmod +x xxx.js
-
Use NRM use NPM to switch the NPM source to the original source
-
NPM adduser Logs in to the NPM
-
NPM released the publish
How do I distribute a TS NPM package
- Install typescript globally
- Run TSC –init to initialize a tsconfig.json
- Create a dist directory and change outDir in config to “dist/”
- Run tsc-p.
- Change files in package.json to [“dist/**/*.js”]
- The rest is the same as publishing normal packages