title: Run js code in a separate context and access its global variable
body: <p>I would like to run a third-party JavaScript file (I don't have much control over its contents) in node and access a global variable created by that file's code in its context.</p>
  
  <p>There are two things I've considered:</p>
  
  <ol>
  <li><p>Running the code in a <a href="https://nodejs.org/api/vm.html" rel="noreferrer"><code>vm</code></a> sandbox. The problem is that I don't know how to <em>properly</em> create the context, because <a href="https://nodejs.org/api/vm.html#vm_vm_createcontext_sandbox" rel="noreferrer"><code>vm.createContext([sandbox])</code></a> won't automatically provide basic things such as <code>console</code> or <code>require</code> or whatever to the script I want to run.</p>
  
  <p>This is a bit of a bummer, because the documentation explicitly states (emphasis mine):</p>
  
  <blockquote>
    <p>If given a sandbox object, will "contextify" that sandbox so that it can be used in calls to vm.runInContext() or script.runInContext(). Inside scripts run as such, sandbox will be the global object, retaining all its existing properties <strong>but also having the built-in objects and functions any standard global object has</strong>.</p>
  </blockquote>
  
  <p>What are <em>"the built-in objects and functions any standard global object has"</em>? I'm naively assuming it's things like <code>console</code>, <code>process</code>, <code>require</code>, etc. But if so, the API doesn't work, because those are not set. I'm probably misunderstanding something here.</p>
  
  <pre><code>var sandbox = vm.createContext({foo: 'foo'});
  var code = 'console.log(foo);';
  vm.runInContext(code, sandbox);
  </code></pre>
  
  <p>Which results in:</p>
  
  <blockquote>
    <p>evalmachine.:1<br>
    console.log(foo);<br>
    ^<br>
    ReferenceError: console is not defined</p>
  </blockquote></li>
  <li><p>Running the code in a <a href="https://nodejs.org/api/child_process.html" rel="noreferrer">child process</a>. But I can't find any documentation on accessing global variables of child processes. I'm assuming the only way to communicate with a child process is by message passing, but even that seems to be from parent to child, not the other way round...</p></li>
  </ol>
  
  <p>Basically, I'm stuck. Halp.</p>