Why does this node CL generate multiple prompts?

I'm noticing a strange behavior in node when working on the command line directly with stdin/stdout. This program should prompt you to enter some text, appends the text to a file fp.txt, then prompt you to do it again ad infinitum

var fs = require('fs'), stdin = process.stdin, stdout = process.stdout;

function prompt() {
  stdout.write('Enter text: ');
  stdin.resume();
  stdin.setEncoding('utf8');
  stdin.on('data', enter);
}

function enter(data) {
  stdin.pause(); // this should terminate stdin
  fs.open('fp.txt', 'a', 0666, function (error, fp) {   
    fs.write(fp, data, null, 'utf-8', function() {
        fs.close(fp, function(error) {
            prompt();
        });
      });
  });
}

prompt();

After the second entry, the prompt will fire twice, then four times. (more than that I get a warning)

Enter text: foo
Enter text: bar
Enter text: Enter text: baz
Enter text: Enter text: Enter text: Enter text: qux

fp.txt shows 1 foo, 2 bar, 4 baz and 8 qux. Is there a way to keep a single text-entry loop going using just process.stdin and process.stdout?

Every time you call prompt() you're adding a new event listener to stdin. Then, every time you're entering something new on the stdin stream, it's calling all the event listeners you've previously added.

You should call it once at the very start of your script instead (you might as well put setEncoding there too):

var fs = require('fs'), stdin = process.stdin, stdout = process.stdout;

stdin.setEncoding('utf8');
stdin.on('data', enter);

function prompt() {
  stdout.write('Enter text: ');
  stdin.resume();
}