2

Related question: Using the Underscore module with Node.js

Is there a way to change the variable Node.js' REPL sets the last return value to? If you could change it from _ to __ or $_, you could then globalize the underscore module so you don't have to set it to a variable in every file: https://gist.github.com/3220108

1
  • If you did this, wouldn't you potentially break modules that are using the underscore for the native REPL? If you want to set a global for underscore, why not use a value that's not already defined in Node, such as the double underscore or $_ as you suggest? Commented Jul 31, 2012 at 21:01

2 Answers 2

3

I figured out a way to do this using the native Node repl module. Instead of just running node at the command line, put this in something like console.js and then run node console.js:

var repl = require('repl')
var vm = require('vm');

var _;

var server = repl.start({
  eval: function (cmd, context, filename, callback) {
    try {
      var match = cmd.match(/^\((.*)\n\)$/);
      var code = match ? match[1] : cmd;
      context._ = _;
      var result = vm.runInThisContext(code, filename);
    } catch (error) {
      console.log(error.stack);
    } finally {
      _ = context._;
      callback(null, result);
    }
  }
}).on('exit', function () {
  process.exit(0);
});

Here's a Gist: https://gist.github.com/jasoncrawford/6818650

Sign up to request clarification or add additional context in comments.

Comments

1

I don't think you can change _ unless you want to edit the source. The node.js REPL appears to be implemented in lib/repl.js; if you poke around the library a little bit, you'll see things like this:

self.context._ = self.context[cmd] = lib;
self.outputStream.write(self.writer(lib) + '\n');

and like this:

self.context._ = ret;
self.outputStream.write(self.writer(ret) + '\n');

The self.context object is the REPL's global context or namespace (similar to window in a browser) so self.context._ = ret; is equivalent to saying _ = ret from the REPL's prompt.

So _ is hardwired and there's nothing you can do about it unless you want to hack the node.js libraries.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.