npm install shelljs -g
npm install shelljs --save
var shell = require('shelljs');
//判定git命令是否可用
if(!shell.which('git')){
//向命令行打印git命令不可用的提示信息
shell.echo('Sorry,this script requires git')
//退出当前进程
shell.exit(1)
}
//先删除'out/Release'目录
shell.rm('-rf','out/Release');
//拷文件到'out/Release'目录
shell.cp('-R','stuff/','out/Release');
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
//切换当前工作目录到'lib'
shell.cd('lib');
//shell.ls('*,js')返回值是一个包含所有js文件路径的数组
shell.js('*.js').forEach(function(file){
//sed命令用于文件内容的替换,这里是对每个文件都只行如下3步操作,更改版本信息
shell.sed('-i','BUILD_VERSION','v0.1.2',file);
})//遍历
shell.cd('..')
//同步执行git命令提交代码
if(shell.exec('git commit -am "Auto-commit').code !==0){
shell.echo('Error: Git commit failed');
shell.exit(1)
}
上面的例子展示了一个可发布版本提交到git仓库的过程。
shelljs的方法都遵循:
方法名是我们常用的执行命令,而方法参数就是命令行参数。只是有些方法对命令行参数做了变形和拓展。
exec()
exec(command [,options][,callback]
callback:< Function >:当进程终止时调用,并带上输出。
ls
shellString(str):用于将常规字符串为ShellString
shellString.prototype.to(file):把ShellString的内容覆盖写入参数指定的file。
cat("input.txt").to("output.txt")
6.ShellString.prototype.toEnd(file):把ShellString的内容写到指定文件的末尾
cat("input.txt").to('output.txt')