Minimist (command line parameter parsing)

gitHub

Process. argv:

// Suppose you have the following script:
process.argv.forEach((val, index) = > {
    console.log(`${index}: ${val}`)})// Start script:
node process-argv.js one two=three four

/ / output:
0: /usr/local/bin/node // process.execPath
1: /Users/mjr/work/node/process-args.js // Address of the script file
2: one
3: two=three
4: four
Copy the code

Process.argv gets the command line arguments to run the script, and process.argv.slice(2) is often used because the second argument is usually needed. Minimist minimist minimist minimist

const args = require('minimist')(process.argv.slice(2))
Copy the code

For example:

node test.js -a a -b b
// args: {_: [], a: 'a', b: 'b'}

node test.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
// { _: [ 'foo', 'bar', 'baz' ],
// x: 3,
// y: 4,
// n: 5,
// a: true,
// b: true,
// c: true,
// beep: 'boop' }
Copy the code

Minimist parses the parameters and puts them into an object that can be easily read in scripts. In particular, the first key is _, and its value is an array containing all the parameters that have no associated options.

Ii. Chalk (Terminal Multi-color output)

gitHub

Used for terminal display multi-color output

Basic usage:

const chalk = require('chalk');

// Basic usage
console.log(chalk.red('red'.'red2'));
console.log(chalk.red('red'));

/ / stitching
console.log(chalk.red('red') + 'middle' + chalk.blue('blue'));

// Multiple styles
console.log(chalk.blue.bgRed.bold('hello world'));

/ /
console.log(chalk.red('Hello', chalk.underline.bgBlue('world') + '! '));
Copy the code

Iii. Enquirer (Terminal Interaction)

gitHub

Interactive ask for user input

Basic usage:

const { prompt } = require('enquirer');

// 1.
const options = {
    type: 'input'.name: 'name'.message: "What's your name?"
}

// 2.
const options = [
    {
      type: 'input'.name: 'username'.message: 'What is your username? '
    },
    {
      type: 'password'.name: 'password'.message: 'What is your password? '}]const res = await prompt(options);
console.log(res);
Copy the code

Another way to call:

// For example, input:
const { Input } = require('enquirer');
const prompt = new Input({
  message: 'What is your username? '.initial: 'jonschlinkert'
});

prompt.run()
  .then(answer= > console.log('Answer:', answer))
  .catch(console.log);
Copy the code

Each query needs to specify a type type or introduce a Prompt class. Common ones are:

  1. Input: Common input, returnedStringtype
  2. Password: Indicates that the password is enteredStringtype
  3. Confirm: Confirm and returnBooleantype
  4. AutoComplete: Automatic completion
  5. BasicAuth: Basic authentication (user name and password)
  6. Form: the form
  7. Invisible: Invisible information
  8. MultiSelect: Select multiple
  9. Numeral: digital

Execa (Execute command)

gitHub

We type in a command at a terminal and execute it

First look at the original:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

const res = await exec('ls');
// 1. You can pass in the directory specified by the CWD argument
const res = await exec('ls', {cwd: path.resolve(__dirname, '.. /.. /test')})
// 2. Another way to specify the execution directory is process.chdir().
process.chdir('.. /.. /test');
const res = await exec('ls');
Copy the code

Key differences or advantages from native EXEC:

  1. Promise to support
  2. Higher maximum buffer. 100mb instead of 200kb.
  3. Execute locally installed binaries by name.
  4. Clears a derived process when the parent terminates.
  5. More descriptive errors.

Basic API and usage:

  1. execa(file, arguments? , options?)
const { stdout } = await execa('git'['status']);
// Specify the execution directory again by passing CWD or process.chdir();
const { stdout } = await execa('git'['status'] and {cwd: resolve('.. /demo')});
Copy the code
  1. execa.sync(file, arguments? , options?) : Synchronizes execution files
  2. Execa.com mand (command options?) : withexeca()Same, except that the files and parameters are specified in a single command string
execa.command('git status');
Copy the code
  1. Execa.com mandSync (command options?) : withexeca.command()Same, but synchronized.

5, fs-extra(operation file)

gitHub

Fs-extra is a degraded version of native FS, with all the methods in FS attached to FS-Extra and promise support added to FS. If no callback is passed in, all fs methods return a promise.

Let’s review some common approaches to native FS:

  1. Get the file type:
const resolve = p= > path.resolve(__dirname, p);

const stat = fs.statSync(resolve('.. /.. /README.txt'));
console.log(stat.isDirectory()); // Whether it is a folder
console.log(stat.isFile()); // Whether it is a file
Copy the code
  1. Whether a file or directory exists:
console.log(fs.existsSync(resolve('.. /fs/fs.js')));
Copy the code
  1. Gets all file names in the directory
fs.readdirSync(path.resolve(__dirname, '.. /fs'));
Copy the code
  1. Read and write (copy files)
const source = fs.readFileSync(resolve('./fs.js')); // Returns a Buffer object
fs.writeFileSync(resolve('./test.js'), source);
Copy the code
  1. Flow, speaking, reading and writing
const readStream = fs.createReadStream(resolve('./1.png');
readStream.on('error'.(err) = > { / / to monitor the error
   console.log('Stream read failed:', err);
})
 
const writeStream = fs.createWriteStream('./2.png');
writeStream.on('error'.(err) = > {
   console.log('Stream write failed:', err);
    })
writeStream.on('close'.(data) = > {
console.log('Stream write complete', data);
 })
readStream.pipe(writeStream);
Copy the code
  1. rename
fs.renameSync(resolve('./old.js'),resolve('./new.js'));
Copy the code
  1. Create a file/directory
fs.mkdirSync(resolve('./newDir');
// Write the file (overwrite the previous content) and create the file if it does not exist
fs.writeFileSync(resolve('./new.js'.'console.log(1)');
Copy the code
  1. Delete files or directories
fs.unlinkSync(resolve('./newDir/test.js')); // Delete files
// Only empty folders can be deleted. To delete a non-empty folder, first delete the files in the folder and then delete the empty folder
fs.rmdirSync(resolve('./newDir'));
Copy the code
  1. Append file contents
const context = `console.log(111)`;
fs.appendFileSync(resolve('./new.js'), context);
Copy the code

Let’s take a look at some common APIS for Fs-Extra:

  1. Copy (SRC, dest[, options][, callback]) : copies files/folders
const fse = require('fs-extra');

// With a callback:
fs.copy('/tmp/myfile'.'/tmp/mynewfile'.err= > {
  if (err) return console.error(err)
  console.log('success! ')})// copies file
fs.copy('/tmp/mydir'.'/tmp/mynewdir'.err= > {
  if (err) return console.error(err)
  console.log('success! ')})// copies directory, even if it has subdirectories or files

// With Promises:
fs.copy('/tmp/myfile'.'/tmp/mynewfile')
.then(() = > {
  console.log('success! ')
})
.catch(err= > {
  console.error(err)
})

// With async/await:
async function example () {
  try {
    await fs.copy('/tmp/myfile'.'/tmp/mynewfile')
    console.log('success! ')}catch (err) {
    console.error(err)
  }
}

example()
Copy the code
  1. EmptyDir (dir[, callback]) : Clears the directory

Make sure the directory is empty. If the directory is not empty, delete all contents in the directory. If the directory does not exist, create an empty directory.

  1. EnsureFile (file[, callback]) : Creates a file

Make sure the file exists. If the directory where the files to be added reside does not exist, create the directory. If the file already exists, no operation is performed.

  1. EnsureDir (dir[,options][,callback]) : create a directory

Make sure the directory exists. If it does not exist, create it.

  1. Remove (path[, callback]) : deletes files/directories

You can delete directories with content (better than FS). If the file/directory exists, no operation is performed.

This article will cover the basic usage of a few common libraries. There are many other ways to use these libraries. For a more complete view, click on the gitHub address of the corresponding library.