Created
October 2, 2011 07:18
-
-
Save jinwei233/1257179 to your computer and use it in GitHub Desktop.
命令行自动完成(二级),带询问
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var rl = require('readline'); | |
// 一级提示 | |
var completionsCMD = ["help","deploy","compress","console"]; | |
var completionsFILES = ["abc.js","bca.js","cba.js"]; | |
var rli = rl.createInterface(process.stdin,process.stdout,function(line){ | |
// excute when Tab pressed | |
// only process the last one | |
_line = line;//for restore | |
line = line.trim().replace(/\s{2,}/g,' '); | |
var words = line.split(" "); | |
var last = words[words.length - 1]; | |
var pre = _line.slice(0,_line.lastIndexOf(last)); | |
var re = new RegExp("^"+last); | |
var completions = words.length > 1 ? completionsFILES : completionsCMD; | |
var result = []; | |
completions.forEach(function(i){ | |
if(re.test(i)){ | |
result.push(pre+i); | |
} | |
}); | |
// console.log("completions:",completions," ; last:",last," ; result:",result,"\n"); | |
return [result,_line]; | |
}); | |
rli.setPrompt(">"); | |
rli.prompt(); | |
process.stdin.resume(); | |
rli.on("SIGINT",function(){ | |
rli.close(); | |
}); | |
rli.addListener("line",function(cmd){ | |
//读取命令字符,根据cmd进行相关操作 | |
rli.question(questionMSG,function(){ | |
console.log("s:",arguments[0],"\n"); | |
var s = arguments[0].trim(); | |
if(s != 'y' && s != "n"){ | |
rli.question(questionMSG+'(please type "y" or "n") ',arguments.callee); | |
}else{ | |
console.log("yes you did it !\n"); | |
rli.prompt(); | |
} | |
}); | |
//操作完成后,显示提示符 | |
rli.prompt(); | |
}); | |
var questionMSG = 'are u ok? y/n '; | |
function question(q,handler){ | |
rli.question(q,questionHandle) | |
} | |
function questionHandle(s){ | |
if(s != 'y' || s != "n"){ | |
question(questionMSG+'(please type "y" or "n")'); | |
} | |
} | |
rli.addListener("close",function(){ | |
process.stdin.destroy(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment