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
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
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.