Home > Article > Web Front-end > Node makes a personalized command line tool
This time I will bring you node to create a personalized command line tool. What are the precautions for node to create a personalized command line tool? The following is a practical case, let’s take a look.
1. Implement a simple function
##2. Environment
1. System: window 102. Editor: vscode
3.node version: 8.7.0
三, Start playing
1. Open the command line and create a new pa'ckage.jsonnpm initAt this time, you will see a new package.json generated, use edit Open the browser2. Modify package.json and add a bin attribute
{ "name": "my-cli", "version": "1.0.0", "description": "", "main": "index.js", "bin": { // 增加bin属性 "auto": "./bin/cli.js" // 左边的crp是定义的命令行的名字,可以自己随便取, 右边是命令行输入 crp 时会执行的文件(一定要在bin文件夹下) }, "scripts": { }, "keywords": [], "author": "", "license": "ISC" }3. Create a new cli.js in the current directory and simply modify it
console.log('hello world')4 .Then go to the command line and enter
npm link5 to check the effect It is successful if hello world is printed correctly6. The principle of realizing the preview effect is that when cli.js is executed, the template set by yourself will be read, and then a file will be generated in the current directory, and the content of the template will be written. , the simple code is as follows
#! /usr/bin/env node const fs = require('fs') const exec = require('child_process').exec var args = process.argv.slice(2) // 可以通过process.argv这里获得你输入的参数 //读取内容(在当前的目录下新建template文件夹和加入一个template.vue的模板) var content = fs.readFileSync('./template/template.vue') //生成内容 fs.writeFileSync(args[0], content) // 使用vscode打开 exec('code ' + args[0])I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website! Recommended reading:
Detailed explanation of the use of CSS cascading mechanism
How to determine the user's sliding direction in H5 touch events
The above is the detailed content of Node makes a personalized command line tool. For more information, please follow other related articles on the PHP Chinese website!