Browse Source

Execute repl code in new context

v0.7.4-release
isaacs 15 years ago
committed by Ryan Dahl
parent
commit
82813f2f8c
  1. 33
      lib/repl.js

33
lib/repl.js

@ -13,14 +13,25 @@
// repl.start("node > ").scope.foo = "stdin is fun"; // expose foo to repl scope // repl.start("node > ").scope.foo = "stdin is fun"; // expose foo to repl scope
var sys = require('sys'); var sys = require('sys');
var evalcx = process.binding('evals').Script.runInNewContext;
var path = require("path");
var scope;
function setScope (self) {
scope = {};
for (var i in global) scope[i] = global[i];
scope.module = module;
scope.require = require;
}
// Can overridden with custom print functions, such as `probe` or `eyes.js` // Can overridden with custom print functions, such as `probe` or `eyes.js`
exports.writer = sys.inspect; exports.writer = sys.inspect;
function REPLServer(prompt, stream) { function REPLServer(prompt, stream) {
var self = this; var self = this;
if (!scope) setScope();
self.scope = {}; self.scope = scope;
self.buffered_cmd = ''; self.buffered_cmd = '';
self.prompt = prompt || "node> "; self.prompt = prompt || "node> ";
self.stream = stream || process.openStdin(); self.stream = stream || process.openStdin();
@ -61,20 +72,20 @@ REPLServer.prototype.readline = function (cmd) {
// This try is for determining if the command is complete, or should // This try is for determining if the command is complete, or should
// continue onto the next line. // continue onto the next line.
try { try {
self.buffered_cmd = self.convertToScope(self.buffered_cmd); // Scope the readline with self.scope
// with(){} and eval() are considered bad.
// Scope the readline with self.scope to provide "local" vars and make Douglas Crockford cry var ret = evalcx(self.buffered_cmd, scope, "repl");
with (self.scope) {
var ret = eval(self.buffered_cmd);
if (ret !== undefined) { if (ret !== undefined) {
self.scope['_'] = ret; scope._ = ret;
self.stream.write(exports.writer(ret) + "\n"); self.stream.write(exports.writer(ret) + "\n");
} }
}
self.buffered_cmd = ''; self.buffered_cmd = '';
} catch (e) { } catch (e) {
if (!(e instanceof SyntaxError)) throw e; // instanceof doesn't work across context switches.
if (!(e && e.constructor && e.constructor.name === "SyntaxError")) {
throw e;
}
} }
} catch (e) { } catch (e) {
// On error: Print the error and clear the buffer // On error: Print the error and clear the buffer
@ -107,7 +118,7 @@ REPLServer.prototype.parseREPLKeyword = function (cmd) {
case ".clear": case ".clear":
self.stream.write("Clearing Scope...\n"); self.stream.write("Clearing Scope...\n");
self.buffered_cmd = ''; self.buffered_cmd = '';
self.scope = {}; setScope();
self.displayPrompt(); self.displayPrompt();
return true; return true;
case ".exit": case ".exit":

Loading…
Cancel
Save