× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

What Node Module provides a CLI prompt?

Asad Saeeduddin
Oct 08, 2015
<p>You could use the standard REPL module and plug in a custom command evaluator. The "up arrow to repeat commands" and such is already baked into the repl module, so you don't need to worry about that.</p> <p>For example, here's a crappily implemented evaluator that does the things you've described in your question:</p> <pre><code>var repl = require("repl"); var cmds = { "help" : function(input, context) { return "debug [setting] Enables or disables debugging..." }, "debug" : function(input, context) { var args = input.split(/\s+/).slice(1); var onoff = args[0]; var verbosity = args[2]; return "Debugging turned " + onoff + " with a verbosity of " + verbosity; }, "exit": function(input, context) { process.exit(); }, "default" : function(input, context) { return "Command not understood"; } }; function eval(input, context, filename, callback) { var cmd = input.split(/\s+/)[0]; var result = (cmds[cmd] || cmds["default"])(input, context); callback(null, result); } repl.start({ prompt: "server:~$ ", eval: eval }); </code></pre> <p>Please note the focus of the demo here is how to implement a custom REPL; there are obviously better ways to implement the evaluator than whitespace splitting and a hash of functions, but how you implement the command evaluator depends on what your application is supposed to do</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30356908/What%20Node%20Module%20provides%20a%20CLI%20prompt?/30700171">Stack Overflow</a>.</p>
comments powered by Disqus