使用node.js创建命令行脚本

552 阅读1分钟

通过npm init命令生成package.json文件

{
	"name": "generator",
	"bin": {
		"testSehll": "./index.js"
	},
	"version": "1.2.3",
	"description": "generate different kinds of project",
	"main": "index.js",
	"scripts": {
		"test": "echo \"Error: no test specified\" && exit 1"
	},
	"author": "1",
	"license": "ISC",
	"dependencies": {
		"shelljs": "^0.8.2",
		"yargs": "^11.0.0"
	}
}

创建index.js文件。

#!/usr/bin/env node
var shell = require('shelljs')
const argv = require('yargs').argv
if ( argv['gw'] ) {
  shell.echo('master模板生成中...')
  getFiles('git clone -q --branch master https://github.com/guosasa/all-css-problems.git')
} else {
  shell.echo('其他模板生成中...')
  getFiles('git clone -q --branch master https://github.com/guosasa/an-app-website')
}

function getFiles (cl) {
  shell.exec(cl, {async: true}, function (code, stdout, stderr) {
    if ( stderr ) {
      shell.echo('生成失败!')
      shell.rm('-rf', 'webpack-Demo')
      shell.exit(1)
    } else {
      shell.echo('生成成功!')
    }
    // console.log(stderr)
    shell.cd('webpack-Demo')
    shell.rm('-rf', '.git')
    shell.cd('..')
    shell.cp('-rf', './webpack-Demo/.', './')
    shell.rm('-rf', 'webpack-Demo')
  })
}

安装好我们的依赖,如果想要放在全局,记放在全局对应的指定目录
执行如下命令

$ npm install -g
$ testSehll

在当前目录下就能生成 git clone的的其他模板。如果 后面加上命令 testSehll gw 就会生成上面master日志中的仓库内容。
参考文档:
使用Node.js创建命令行脚本工具