Home > Web Front-end > JS Tutorial > Tutorial on how to use node to build your own command line tool

Tutorial on how to use node to build your own command line tool

亚连
Release: 2018-05-28 17:25:24
Original
1706 people have browsed it

This article mainly introduces the tutorial on how to use node to build your own command line tool. Now I share it with you and give it as a reference.

1. Implement a simple function

##2. Environment

1. System: window 10

2. Editor: vscode
3.node version: 8.7.0

三, Start playing

1. Open the command line and create a new pa'ckage.json

npm init
Copy after login

Look at this A new package.json is generated, use the editor to open it

2. Modify the 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"
  }
Copy after login

3. Create a new cli.js in the current directory and simply modify

console.log('hello world')
Copy after login

4. Then go to the command line and enter

npm link
Copy after login

5 Check the effect



##It is successful if hello world is printed correctly


6. To achieve the preview effect

The principle is that when executing cli.js, it will read the template you set and then generate a file in the current directory,


Write the content of the template, 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])
Copy after login

The above is what I compiled for everyone, I hope it will be useful to everyone in the future helpful.

Related articles:

Using the H5 feature FormData to upload files without refreshing


Realizing mobile phone positioning based on h5 ajax


AJAX cross-domain request JSONP to obtain JSON data


The above is the detailed content of Tutorial on how to use node to build your own command line tool. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template