Tuesday, 3 September 2013

Javascript VM object returned has wrong reference?

Javascript VM object returned has wrong reference?

Back again with another tedious problem. It's easier if I explain the
context before the problem. I'm trying to build a project (in Node.JS)
that allows you to program itself, from inside itself via an "input" (this
could be network/console or anything really, but lets assume via a console
for this).
So let's imagine we have an object:
var database = {
'test': 123
}
Now from the console I type:
;database.myFunc = function() { return database.test; }
I run this using vm.runInContext and copy it back into the database object
afterwards (it needs to be sandbox'd because it's non-privileged users
running it). This works fine, and the code works fine when executed in the
next command:
;database.myFunc()
=> 123
All good so far. Now at this point I built my own object dumper that can
export functions as strings (var str = new String(database.myFunc)), which
works and exports them as strings.
This issue comes when I import the code from a file. I've tried code like
this:
code = "retval = " + data.toString();
sandbox = vm.createContext({
"database": sb.database
});
result = vm.runInNewContext(code, sandbox);
sb.database = result;
console.log(sb.database.myfunc());
It appears the code that runs, only has access to the database i copied
into the sandbox. This isn't what I want, I want it to access the same DB
it had at the first runtime. Any suggestions as to how I'd do that?

No comments:

Post a Comment