SoFunction
Updated on 2025-03-03

Detailed explanation of command line program development tutorial

Whether a programming language is easy to use depends largely on the ability to develop command-line programs.

As one of the most popular development tools at present, how to use it to develop command line programs is a skill that web developers should master.

The following is the tutorial I expanded on it, which should be the best solution at present.

1. Executable scripts

Let's start with the simplest.

First, write an executable script using the JavaScript language hello.

#!/usr/bin/env node
('hello world');

Then, modify the permissions of hello.

$ chmod 755 hello

Now hello can be executed.

$ ./hello
hello world

If you want to remove the path in front of hello, you can add the path in hello to the environment variable PATH. However, another better approach is to create a new one in the current directory and write the following content.

{
 "name": "hello",
 "bin": {
  "hello": "hello"
 }
}

Then execute the npm link command.

$ npm link

Now execute hello again, you don’t need to enter the path.

$ hello
hello world

2. Original writing of command line parameters

Command line parameters can be obtained using system variables.

Below is a script hello.

#!/usr/bin/env node
('hello ', [2]);

When executing, just add parameters after the script file.

$ ./hello tom
hello tom

In the above code, the actual execution of node ./hello tom , which corresponds to ['node', '/path/to/hello', 'tom'] .

3. Create a new process

The script can create new child processes through the child_process module to execute Unix system commands.

#!/usr/bin/env node
var name = [2];
var exec = require('child_process').exec;

var child = exec('echo hello ' + name, function(err, stdout, stderr) {
 if (err) throw err;
 (stdout);
});

The usage is as follows.

$ ./hello tom
hello tom

4. Shelljs module

The shelljs module has repackaged child_process, making calling system commands more convenient. It needs to be installed and used.

npm install --save shelljs

Then, rewrite the script.

#!/usr/bin/env node
var name = [2];
var shell = require("shelljs");

("echo hello " + name);

The above code is the local pattern of shelljs, that is, the shell command is executed through the exec method. There is also a global mode that allows writing shell commands directly in scripts.

require('shelljs/global');

if (!which('git')) {
 echo('Sorry, this script requires git');
 exit(1);
}

mkdir('-p', 'out/Release');
cp('-R', 'stuff/*', 'out/Release');

cd('lib');
ls('*.js').forEach(function(file) {
 sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
 sed('-i', /.*REMOVE_THIS_LINE.*\n/, '', file);
 sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat(''), file);
});
cd('..');

if (exec('git commit -am "Auto-commit"').code !== 0) {
 echo('Error: Git commit failed');
 exit(1);
}

5. Yargs module

shelljs only solves how to call shell commands, while yargs module solves how to handle command line parameters. It also needs to be installed.

$ npm install --save yargs

The yargs module provides an argv object to read command line parameters. Please see the rewrite hello.

#!/usr/bin/env node
var argv = require('yargs').argv;

('hello ', );

When using it, both of the following usages are OK.

$ hello --name=tom
hello tom

$ hello --name tom
hello tom

That is, the original return value of , is as follows.

$ node hello --name=tom
[ 'node',
 '/path/to/',
 '--name=tom' ]

yargs The above result can be changed to an object, and each parameter item is a key-value pair.

var argv = require('yargs').argv;

// $ node hello --name=tom
// argv = {
//  name: tom
// };

If you change to , you can use a short parameter form of a letter.

$ hello -n tom
hello tom

You can use the alias method to specify that name is an alias name.

#!/usr/bin/env node
var argv = require('yargs')
 .alias('n', 'name')
 .argv;

('hello ', );

In this way, both short and long parameters can be used.

$ hello -n tom
hello tom
$ hello --name tom
hello tom

The argv object has an underscore (_) attribute that can obtain parameters starting with non-conjunction lines.

#!/usr/bin/env node
var argv = require('yargs').argv;

('hello ', );
(argv._);

The usage is as follows.

$ hello A -n tom B C
hello tom
[ 'A', 'B', 'C' ]

6. Configuration of command line parameters

The yargs module also provides 3 methods to configure command line parameters.

  1. Demand: Whether it is required
  2. default: default value
  3. describe: Tip
#!/usr/bin/env node
var argv = require('yargs')
 .demand(['n'])
 .default({n: 'tom'})
 .describe({n: 'your name'})
 .argv;

('hello ', );

The above code specifies that n parameters cannot be omitted, the default value is tom, and a line of prompts are given.

The options method allows all these configurations to be written into an object.

#!/usr/bin/env node
var argv = require('yargs')
 .option('n', {
  alias : 'name',
  demand: true,
  default: 'tom',
  describe: 'your name',
  type: 'string'
 })
 .argv;

('hello ', );

Sometimes, some parameters do not need values, and only serve as a switch. At this time, you can use the boolean method to specify these parameters to return Boolean values.

#!/usr/bin/env node
var argv = require('yargs')
 .boolean(['n'])
 .argv;

('hello ', );

In the above code, parameter n always returns a Boolean value, and the usage is as follows.

$ hello
hello false
$ hello -n
hello true
$ hello -n tom
hello true

The boolean method can also be used as a property to write to an option object.

#!/usr/bin/env node
var argv = require('yargs')
 .option('n', {
  boolean: true
 })
 .argv;

('hello ', );

7. Help information

The yargs module provides the following methods to generate help information.

  1. usage: Usage format
  2. example: provide examples
  3. help: Show help information
  4. epilog: appears at the end of the help message
#!/usr/bin/env node
var argv = require('yargs')
 .option('f', {
  alias : 'name',
  demand: true,
  default: 'tom',
  describe: 'your name',
  type: 'string'
 })
 .usage('Usage: hello [options]')
 .example('hello -n tom', 'say hello to Tom')
 .help('h')
 .alias('h', 'help')
 .epilog('copyright 2015')
 .argv;

('hello ', );

The execution results are as follows.

$ hello -h

Usage: hello [options]

Options:
 -f, --name your name [string] [required] [default: "tom"]
 -h, --help Show help [boolean]

Examples:
 hello -n tom say hello to Tom

copyright 2015

8. Sub-order

The yargs module also allows Git-style subcommands to be set through the command method.

#!/usr/bin/env node
var argv = require('yargs')
 .command("morning", "good morning", function (yargs) {
  ("Good Morning");
 })
 .command("evening", "good evening", function (yargs) {
  ("Good Evening");
 })
 .argv;

('hello ', );

The usage is as follows.

$ hello morning -n tom
Good Morning
hello tom

This function can be combined with the shellojs module.

#!/usr/bin/env node
require('shelljs/global');
var argv = require('yargs')
 .command("morning", "good morning", function (yargs) {
  echo("Good Morning");
 })
 .command("evening", "good evening", function (yargs) {
  echo("Good Evening");
 })
 .argv;

('hello ', );

Each subcommand often has its own parameters, which need to be specified separately in the callback function. In the callback function, you must first use the reset method to reset the yargs object.

#!/usr/bin/env node
require('shelljs/global');
var argv = require('yargs')
 .command("morning", "good morning", function (yargs) { 
  echo("Good Morning");
  var argv = ()
   .option("m", {
    alias: "message",
    description: "provide any sentence"
   })
   .help("h")
   .alias("h", "help")
   .argv;

  echo();
 })
 .argv;

The usage is as follows.

$ hello morning -m "Are you hungry?"
Good Morning
Are you hungry?

9. Other matters

(1) Return value

According to Unix tradition, program execution returns 0 if successful, otherwise 1 if returned.

if (err) {
 (1);
} else {
 (0);
}

(2) Redirect

Unix allows pipeline redirecting data between programs.

$ ps aux | grep 'node'

The script can obtain redirected data by listening to the standard input data events.

();
('utf8');
('data', function(data) {
 (data);
});

The following is the usage.

$ echo 'foo' | ./hello
hello foo

(3) System signal

The operating system can send signals to the executed process, and the process object can listen for signal events.

('SIGINT', function () {
 ('Got a SIGINT');
 (0);
});

The method of sending a signal is as follows.

$ kill -s SIGINT [process_id]

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.