repl: add a 'writer' option to the repl

Previously this was a module-level setting, meaning that all REPL instances
had to share the same writer function. Turning it into one of the options
allows individual REPL instances to use their own writer function.
This commit is contained in:
Nathan Rajlich 2012-03-27 17:39:14 -07:00
parent 228ddddc1c
commit b187e96ec9
2 changed files with 13 additions and 5 deletions

View File

@ -53,6 +53,10 @@ takes the following values:
- `ignoreUndefined` - if set to `true`, then the repl will not output the
return value of command if it's `undefined`. Defaults to `false`.
- `writer` - the function to invoke for each command that gets evaluated which
returns the formatting (including coloring) to display. Defaults to
`util.inspect`.
You can use your own `eval` function if it has following signature:
function eval(cmd, context, filename, callback) {

View File

@ -66,7 +66,8 @@ module.filename = path.resolve('repl');
// hack for repl require to work properly with node_modules folders
module.paths = require('module')._nodeModulePaths(module.filename);
// Can overridden with custom print functions, such as `probe` or `eyes.js`
// Can overridden with custom print functions, such as `probe` or `eyes.js`.
// This is the default "writer" value if none is passed in the REPL options.
exports.writer = util.inspect;
exports._builtinLibs = ['assert', 'buffer', 'child_process', 'cluster',
@ -159,10 +160,13 @@ function REPLServer(prompt, stream, eval, useGlobal, ignoreUndefined) {
this.commands = {};
defineDefaultCommands(this);
// figure out which "writer" function to use
self.writer = options.writer || exports.writer;
if (rli.terminal && !exports.disableColors &&
exports.writer === util.inspect) {
self.writer === util.inspect) {
// Turn on ANSI coloring.
exports.writer = function(obj, showHidden, depth) {
self.writer = function(obj, showHidden, depth) {
return util.inspect(obj, showHidden, depth, true);
};
}
@ -224,7 +228,7 @@ function REPLServer(prompt, stream, eval, useGlobal, ignoreUndefined) {
'" already exists globally\n');
} else {
self.context._ = self.context[cmd] = lib;
self.outputStream.write(exports.writer(lib) + '\n');
self.outputStream.write(self.writer(lib) + '\n');
}
self.displayPrompt();
return;
@ -293,7 +297,7 @@ function REPLServer(prompt, stream, eval, useGlobal, ignoreUndefined) {
// If we got any output - print it (if no error)
if (!e && (!self.ignoreUndefined || ret !== undefined)) {
self.context._ = ret;
self.outputStream.write(exports.writer(ret) + '\n');
self.outputStream.write(self.writer(ret) + '\n');
}
// Display prompt again