blog.gvm-it.eu
Keyboard input module for node: node-prompt.js

I have been watching node.js very close over the past weeks and eventually got myself a working installation, so it was about time to code something. But what? Don’t ask why, but I ended up writing a simple module that allows you to prompt input in your node process window.

Basically, what I wanted to have was the possibility to start up a node.js program and manually enter data without having to pass it via the command line. For example, one might want to enter a server adres or a password when you fire up your script.

In the example below, the program asks for your favorite color and a secret, which does not display the text that you entered:

The corresponding code (example.js in the .zip package) looks something like this:

// include node-prompt.js
var nodePrompt = require('./node-prompt.js');

// open an input prompt
nodePrompt.prompt(
	"What is your favorite color?", 
	function(response) {
	
		// print the entered text
		console.log(response + " really is a nice color.");
		
		// example asking for a password
		nodePrompt.password(
			"Now tell me a secret!", 
			function(password) {
			
				// print out the entered text
				console.log("Did you hear that? " 
					+ password.toUpperCase() 
					+ "! That\'s just ridiculous!");
		});
});

The sourcecode for node-prompt.js is included in this node-prompt.js.zip (2.4kb) package. Extract it anywhere and run example.js with node. If this is something which node users find useful, I will eventually create a npm package for it, but for now I’ll rest with it.

Feedback is appreciated!

Blog comments powered by Disqus