How to develop a Node scaffold

Keywords: node.js cli

reason

In the work, a scaffold needs to be developed to provide relevant development convenience to relevant users.

Suitable for people

Have a certain understanding of the front-end and Node operations, and want to understand the scaffold development process or need to implement a scaffold developer.

target

  1. Develop a simple scaffold that can be provided to users for installation.

  2. Be able to output relevant prompts.

  3. Read and write user files.

  4. Use Shell scripts in scaffolding.

step

Development scaffold

The initial process of scaffold development is the same as that of ordinary front-end projects. An entry file command.js and a configuration file package.json are required.

Different from other configuration files, you need to add the following declaration in the first line of the command.js file:

#! /usr/bin/env node

At the same time, the following items need to be added to the package.json file:

{
  ...,
  "bin": {
     "cm-cli": "command.js"
   }
}

After adding this item in the configuration file, you only need to execute the npm link command in the root directory of the configuration file, and you can use the CM cli -- help command to view the loaded cm cli scaffold (you need to ensure that command.js can process the response. See the next section for details, which is placed here for the convenience of reading the chapter).

If you publish your scaffold, you can use your scaffold globally after other users use the command NPM install - g cm cli.

Prompt the user

In the prompt for comments and commands, we need to use the commander package and use npm install commander to install. (if the NPM version is lower than 5, you need to add the -- save parameter to ensure that the package.json configuration file is updated).

commander is a powerful function that provides user command line input and parameter parsing. If necessary, you can read the relevant library documents. Here I introduce the two most used methods.

option

It can initialize user-defined parameter objects, set keywords and descriptions, and set and read parameters entered by users. The specific usage is as follows:

const commander = require('commander');

commander.version('1.0.0')
    .option('-a, --aaa', 'aaaaa')
    .option('-b, --bbb', 'bbbbb')
    .option('-c, --ccc [name]', 'ccccc')
    .parse(process.argv);

if (commander.aaa) {
    console.log('aaa');
}

if (commander.bbb) {
    console.log('bbb');
}

if (commander.ccc) {
    console.log('ccc', commander.ccc);
}

At this time, if the configuration is completed and the npm link command is executed, you can see the following results:

command

This method can add a command on the command line. After executing this command, the user can execute the logic in the callback. The specific usage is as follows:

commander
    .command('init <extensionId>')
    .description('init extension project')
    .action((extensionId) => {
        console.log(`init Extension Project "${extensionId}"`);
    // todo something you need
    });

The specific display effects are as follows:

Read and write user files

Through the above steps, we have been able to complete a simple scaffold. Next, we need to read the user configuration and generate some template files for the user.

read file

Now, we need to read the user's cm-cli.json configuration file to make some configuration.

We can use the fs file module of Node.js to read the file progress. Since there are not many difficulties here, we omit them.

Write file template

We store the template file on the CDN in advance, and then download the template according to the relevant scaffold configuration file read locally.

Note: the path read in the scaffold is the current path used by the user, so there is no way to store the template file in the scaffold for reading.

We can use libraries such as request to help us download files and simplify the operation steps. Execute npm install request to install.

Note: when writing a file, it is recommended to judge whether the file exists before overwriting it.

Using Shell scripts

Compared with the API functions provided by Node.js, some people prefer to use Shell scripts for file operations. Fortunately, we can also introduce node CMD into our scaffolding to enable support for Shell scripts. Execute NPM install node CMD to install.

Specific examples are as follows:

commander
    .command('init <extensionId>')
    .description('init extension project')
    .action((extensionId) => {
        id = extensionId;
        console.log(`init Extension Project "${extensionId}"`);

        cmd.get(
            `
            mkdir -p static/${extensionId}

            mkdir tmp
            mkdir tmp/source-file
            mkdir tmp/build-file
            curl -o tmp/source-file/index.js https://xxxxxxxx.com?filename=index.js
            touch tmp/source-file/index.css

            curl -o tmp/build-file/server.js https://xxxxxxxx.com?filename=server.js
            curl -o tmp/build-file/router.js https://xxxxxxxx.com?filename=router.js
            curl -o tmp/build-file/package.json https://xxxxxxxx.com?filename=package.json
            
            cp  tmp/source-file/* static/${extensionId}
            cp tmp/build-file/* ./
            rm -fr tmp
            npm install
            `,
            (err, data) => {
                console.log(data)
                if (!err) {
                    console.log('init success');
                    return;
                }

                console.error('init error');
            });
    });

We can quickly use Shell scripts to create folders and download file templates.

summary

If you want to execute the scaffold quickly on the terminal, you can add relevant fields in the package.json configuration file.

The scaffold needs to be able to read the relevant terminal input, which can be developed quickly using the commander library.

The scaffold needs to be able to execute Shell scripts, and the node CMD library can be used to quickly implement the requirements.

Posted by intellivision on Wed, 29 Sep 2021 10:36:04 -0700