Skip to content

Instantly share code, notes, and snippets.

@jasoncrawford
Last active December 24, 2015 15:18
Show Gist options
  • Save jasoncrawford/6818650 to your computer and use it in GitHub Desktop.
Save jasoncrawford/6818650 to your computer and use it in GitHub Desktop.
Node REPL that doesn't clobber _
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);
});
@jasoncrawford
Copy link
Author

I wrote this for myself because I wanted to load the app I'm working on in the REPL and run code, like you can do in Rails with rails console. But my app sets global._ = require('underscore'), so I don't have to manually require it in every source file, and the Node REPL was clobbering the _ variable.

This code snippet fixes the problem using the native Node repl and vm modules. It saves off the value of _ and restores it each time. Just invoke it like: node console.js

If you have an app and you want to pre-load a bunch of your classes into the global namespace for convenience, just do that here before the REPL is started.

@jasoncrawford
Copy link
Author

Note one deficiency relative to just running node: You can't enter code that spans more than one line. You'll get a syntax error. Haven't figured that one out yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment