hx_watch
Version:
none
143 lines (116 loc) • 2.93 kB
JavaScript
/**
* @description: 文件监听,执行cmd命令小工具
* @author 王鸿兴
* @version 1.0.1
*/
var childProcess = require('child_process');
var fs = require('fs');
var folder,cmd;
try {
var config = fs.readFileSync('config.wh').toString();
var array = config.match(/[a-z]*="[^\n";]*"(?=;)/g);
var configObj = {}
array.forEach(function(a){
configObj[a.split('=')[0]] = trim(a.split('=')[1].replace(/(^")|("$)/g , ''))
})
if(('folder' in configObj)&&('cmd' in configObj)){
folder = configObj.folder;
cmd = configObj.cmd;
console.log('监听文件:'+folder)
console.log('cmd命令:'+cmd)
watchHandle()
}else {
throw new Error("配置文件错误")
}
} catch (e) {
console.log("请输入:文件夹名|命令(例:html|grunt build-html 回车)");
getInput(function(result) {
var data = result.split('|');
if (data.length == 2) {
folder = data[0].replace(/[\r\n]/g,'');
cmd = data[1].replace(/[\r\n]/g,'');
fs.writeFile('config.wh' , 'folder="'+folder+'";\r\ncmd="'+cmd+'";',function(){
watchHandle()
})
} else {
console.log("格式输入有误,请重试")
fileListen()
}
})
}
var paths = [];
function watchHandle() {
console.log("开始监听");
//对改目录下文件进行遍历,监听;
var changing = false;
execCmd();
paths = getAllFolderPath(folder);
paths.forEach(function(path) {
wathPath(path)
});
function wathPath(path){
fs.watch(path, function(event, filename) {
if (changing) return;
if(event=="rename")check();
changing = true;
execCmd();
setTimeout(function() {
changing = false;
}, 1000)
}).on("error",function(){
check();
})
}
function check(){
var npath = getAllFolderPath(folder);
var newwatcher = [];
npath.forEach(function(path){
if(paths.indexOf(path)==-1){
newwatcher.push(path);
}
});
newwatcher.forEach(function(path){
wathPath(path)
});
paths = npath.slice(0,npath.length);
}
}
function execCmd(){
console.log('执行' + cmd);
childProcess.exec(cmd, function(err, stdout, stderr) {
console.log(stdout)
})
}
function trim(msg){
return msg.replace(/(^\s*)|(\s*$)/g , "")
}
//进入输入状态
function getInput(callback) {
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
process.stdin.pause();
callback(chunk);
});
}
//遍历文件夹的目录,获取所有文件夹目录
function getAllFolderPath(folderName) {
var folderPath = [folderName + "/"];
readFilePath(folderName)
return folderPath;
function readFilePath(fn) {
fn += fn.charAt(fn.length - 1) == '/' ? '' : '/';
try {
var files = fs.readdirSync(fn);
for (var i = 0; i < files.length; i++) {
var stat = fs.lstatSync(fn + files[i])
if (stat.isDirectory()) {
folderPath.push(fn + files[i] + '/')
readFilePath(fn + files[i])
}
}
} catch (e) {
console.log(e)
}
}
}