search
HomeBackend DevelopmentPHP TutorialHow to implement a simple Node.js scaffolding

How to implement a simple Node.js scaffolding

Dec 05, 2017 pm 12:03 PM
javascriptnode.jsSimple

This article mainly introduces how to implement a simple Node.js scaffolding. I hope everyone will have a better grasp of Node.js.

At work, a scaffolding needs to be developed to provide relevant development convenience to relevant users.

Suitable for people

Have a certain understanding of front-end and Node operations, and are also interested in developers who understand the scaffolding development process or need to implement a scaffolding themselves.

Goal

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

  2. can output relevant prompts.

  3. Perform reading and writing operations on user files.

  4. Use shell scripts in scaffolding.

Steps

Develop the scaffolding

The beginning of the development of the scaffolding The process is the same as that of a normal front-end project, requiring an entry file command.js and a configuration file package.json.

Different from other configuration files, you need to add the following item to the package.json file:


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


After adding this item to 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 scaffolding.

If you publish your scaffolding, then other users can use your scaffolding globally after using the command npm install -g cm-cli.

Prompt users

In prompting comments and commands, we need to use the commander package, which can be installed using npm install commander. (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 documentation. Here I introduce the two most commonly used methods.

#option

Ability to initialize custom parameter objects, set keywords and descriptions, and also set parameters for reading user input. 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);
}


The specific usage is as follows:

command

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


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


The specific display effect is as follows:

Read and write user files

Through the above steps, we have been able to complete a simple scaffolding. 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 perform 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 will omit it.

Write file template

We store the template file on the CDN in advance, and then proceed with the template based on the relevant scaffolding configuration files read locally. download.

Note: The path read in the scaffold is the current path when the user uses it, 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 first determine whether the file exists before overwriting it.

Using Shell Script

Judging from the API functions provided by Node.js, some people prefer to use Shell scripts to perform 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(&#39;init <extensionId>&#39;)
  .description(&#39;init extension project&#39;)
  .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(&#39;init success&#39;);
          return;
        }

        console.error(&#39;init error&#39;);
      });
  });


We can quickly use Shell scripts to create folders and files Template download.

If you want the scaffolding to be executed quickly in the terminal, you can add relevant fields to the package.json configuration file.

Scaffolding needs to be able to read relevant terminal input, and can use the commander library for rapid development.

The scaffolding needs to be able to execute Shell scripts, and you can use the node-cmd library to quickly implement the requirements.

The above content is how to implement a simple Node.js scaffolding. I hope it will be helpful to everyone.

Related recommendations:

First introduction to node.js

How to use node.js to write a stream createWriteStream

node.js publish-subscribe mode method

The above is the detailed content of How to implement a simple Node.js scaffolding. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools