From b6dafc1a4708a61c1335ced903f464fdd3ebb294 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 6 Jan 2011 13:42:30 -0800 Subject: [PATCH] Allow for two streams in REPL Towards windows compatibility. --- lib/repl.js | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/lib/repl.js b/lib/repl.js index c425603ef5..83f52e8128 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -52,10 +52,19 @@ function REPLServer(prompt, stream) { self.context = context; self.bufferedCommand = ''; - self.stream = stream || process.openStdin(); + if (stream) { + // We're given a duplex socket + self.outputStream = stream; + self.inputStream = stream; + } else { + self.outputStream = process.stdout; + self.inputStream = process.stdin; + process.stdin.resume(); + } + self.prompt = prompt || '> '; - var rli = self.rli = rl.createInterface(self.stream, function(text) { + var rli = self.rli = rl.createInterface(self.outputStream, function(text) { return self.complete(text); }); @@ -81,7 +90,7 @@ function REPLServer(prompt, stream) { } }); - self.stream.addListener('data', function(chunk) { + self.inputStream.addListener('data', function(chunk) { rli.write(chunk); }); @@ -98,7 +107,7 @@ function REPLServer(prompt, stream) { if (self.parseREPLKeyword(keyword, rest) === true) { return; } else { - self.stream.write('Invalid REPL keyword\n'); + self.outputStream.write('Invalid REPL keyword\n'); skipCatchall = true; } } @@ -132,7 +141,7 @@ function REPLServer(prompt, stream) { if (ret !== undefined) { context._ = ret; - self.stream.write(exports.writer(ret) + '\n'); + self.outputStream.write(exports.writer(ret) + '\n'); } self.bufferedCommand = ''; @@ -151,9 +160,9 @@ function REPLServer(prompt, stream) { } catch (e) { // On error: Print the error and clear the buffer if (e.stack) { - self.stream.write(e.stack + '\n'); + self.outputStream.write(e.stack + '\n'); } else { - self.stream.write(e.toString() + '\n'); + self.outputStream.write(e.toString() + '\n'); } self.bufferedCommand = ''; } @@ -163,7 +172,7 @@ function REPLServer(prompt, stream) { }); rli.addListener('close', function() { - self.stream.destroy(); + self.inputStream.destroy(); }); self.displayPrompt(); @@ -465,7 +474,7 @@ function defineDefaultCommands(repl) { repl.defineCommand('clear', { help: 'Break, and also clear the local context', action: function() { - this.stream.write('Clearing context...\n'); + this.outputStream.write('Clearing context...\n'); this.bufferedCommand = ''; resetContext(); this.displayPrompt(); @@ -485,7 +494,7 @@ function defineDefaultCommands(repl) { var self = this; Object.keys(this.commands).sort().forEach(function(name) { var cmd = self.commands[name]; - self.stream.write(name + '\t' + (cmd.help || '') + '\n'); + self.outputStream.write(name + '\t' + (cmd.help || '') + '\n'); }); this.displayPrompt(); }