Source code address.

The purpose of this package is to check whether process.argv contains a specific identifier for terminal parameters.

Use the following

$ node foo.js -f --unicorn --foo=bar -- --rainbow

// foo.js
const hasFlag = require('has-flag');

hasFlag('unicorn');
//=> true

hasFlag('--unicorn');
//=> true

hasFlag('f');
//=> true

hasFlag('-f');
//=> true

hasFlag('foo=bar');
//=> true

hasFlag('foo');
//=> false

hasFlag('rainbow');
//=> false
Copy the code

knowledge

process.argv

Process. argv returns an array containing the arguments passed in when the Node process is started.

The first parameter is process.execPath, which refers to the absolute path to the executable that started the Node process.

The second argument is the absolute path to the file being executed.

The following parameters are the ones passed in, separated by Spaces.

$ node source.js -f --unicorn --foo=bar -- --rainbow
console.log(process.argv)
[
  '/usr/local/bin/node'.'/Users/xuyizong/Documents/code/tets/source.js'.'-f'.'--unicorn'.'--foo=bar'.The '-'.'--rainbow'
]
Copy the code

The source code

'use strict';

module.exports = (flag, argv = process.argv) = > {
  // flag: identifies specific flags or parameters
  // argv defaults to process.argv or passes string[]
  // Handle the prefix of the flag. It is recommended that you bring your own prefix
	const prefix = flag.startsWith(The '-')?' ' : (flag.length === 1 ? The '-' : The '-');
	const position = argv.indexOf(prefix + flag);
	const terminatorPosition = argv.indexOf(The '-');
	returnposition ! = = -1 && (terminatorPosition === -1 || position < terminatorPosition);
};
Copy the code

Process. The stderr, process. Stdout

These two attributes are extended here and will be used later in another package.

The process.stderr property returns the stream connected to stderr(file descriptor 2). It is a net.socket (a Duplex stream) unless the file descriptor 2 points to a file (in which case it is a Writable stream).

process.stderr.fd // 2 Gets the value of the file descriptor for process.stderr, which is useful for some scenarios
Copy the code

The process.stdout property returns the stream connected to stdout(file descriptor 1). It is a net.socket (a Duplex stream) unless file descriptor 1 points to a file (in which case it is a Writable stream).

process.stdout.fd / / 1
Copy the code

Process.stdout and process.stderr are used inside console.log() and console.error() respectively.

so

> tty.isatty(1)
true
> tty.isatty(2)
true
Copy the code

Well, that’s all for today. See you next time.

Ps: If you are also interested in Node, please follow my official account: XYZ Programming Diary.