6.0.0 • Published 2 years ago
node-retrieve-globals v6.0.0
node-retrieve-globals
Execute a string of JavaScript using Node.js and return the global variable values and functions.
- Supported on Node.js 16 and newer.
- Uses
var,let,const,function, Array and Object destructuring assignment. - Async-only as of v5.0.
- Can return any valid JS data type (including functions).
- Can provide an external data object as context to the local execution scope
- Transforms ESM import statements to work with current CommonJS limitations in Node’s
vm. - Uses Node’s
vmmodule to execute JavaScript ⚠️ Thenode:vmmodule is not a security mechanism. Do not use it to run untrusted code.codeGeneration(e.g.eval) is disabled by default; usesetCreateContextOptions({codeGeneration: { strings: true, wasm: true } })to re-enable. Works with or without--experimental-vm-modulesflag (forvm.Modulesupport). (v5.0.0 and newer) Future-friendly feature tests for whenvm.Moduleis stable and--experimental-vm-modulesis no longer necessary. (v5.0.0 and newer) - In use on:
JavaScript in Eleventy Front Matter (and Demo)
WebC’s
<script webc:setup>
Installation
Available on npm
npm install node-retrieve-globalsUsage
Works from Node.js with ESM and CommonJS:
import { RetrieveGlobals } from "node-retrieve-globals";
// const { RetrieveGlobals } = await import("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
// Defaults shown
let options = {
reuseGlobal: false, // re-use Node.js `global`, important if you want `console.log` to log to your console as expected.
dynamicImport: false, // allows `import()`
addRequire: false, // allows `require()`
experimentalModuleApi: false, // uses Module#_compile instead of `vm` (you probably don’t want this and it is bypassed by default when vm.Module is supported)
};
await vm.getGlobalContext({}, options);Changelog
v6.0.0Changesimportandrequireto be project relative (not relative to this package on the file system).v5.0.0Removes sync API, swap to async-only. Better compatibility with--experimental-vm-modulesNode flag.v4.0.0Swap to useModule._compileas a workaround for #2 (Node regression with experimental modules API in Node v20.10+)v3.0.0ESM-only package. Node 16+