Last active
December 24, 2015 15:18
-
-
Save jasoncrawford/6818650 to your computer and use it in GitHub Desktop.
Node REPL that doesn't clobber _
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
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
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
andvm
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.