node-retrieve-globals
Execute a string of JavaScript using Node.js and return the global variable values and functions.
-
Supported on Node.js 14 and newer.
-
Uses var
, let
, const
, function
, Array and Object destructuring assignment.
-
Async-friendly but synchronous methods are available.
-
Can return any valid JS data type (including functions).
-
Can provide an external data object as context to the local execution scope
-
Uses Node’s vm
module to execute JavaScript
- ⚠️ The
node:vm
module is not a security mechanism. Do not use it to run untrusted code. codeGeneration
(e.g. eval
) is disabled by default; use setCreateContextOptions({codeGeneration: { strings: true, wasm: true } })
to re-enable.
-
In use on:
Installation
Available on npm
npm install node-retrieve-globals
Usage
Works from Node.js with ESM and CommonJS:
import { RetrieveGlobals } from "node-retrieve-globals";
And then:
let code = `var a = 1;
const b = "hello";
function hello() {}`;
let vm = new RetrieveGlobals(code);
await vm.getGlobalContext();
Returns:
{ a: 1, b: "hello", hello: function hello() {} }
Pass in your own Data and reference it in the JavaScript code
let code = `let ref = myData;`;
let vm = new RetrieveGlobals(code);
await vm.getGlobalContext({ myData: "hello" });
Returns:
{ ref: "hello" }
Advanced options
let options = {
reuseGlobal: false,
dynamicImport: false,
};
await vm.getGlobalContext({}, options);