patriksimek / vm2

Advanced vm/sandbox for Node.js
MIT License
3.87k stars 295 forks source link

Unable to use node-fetch - string.replace is not a function #476

Closed ZeroSkill830 closed 2 years ago

ZeroSkill830 commented 2 years ago

Hello, i have this script

async function getSignature(address) {
  let response = await fetch(
    `https://633acd46471b8c3955754d84.mockapi.io/signature?address=${address}`
  );
  let signature = await response.json();
  return {
    signature: signature[0],
  };
}

// usage example
getSignature('0x1234').then((res) =>{
  x = res.signature;
});

that i'm trying to running in this way

const { NodeVM } = require("vm2");
  const fetch = require("node-fetch");
  const vm = new NodeVM({
    sandbox: { x: '', fetch },
    require: {
       context: 'sandbox',
      external: [true],
      root: "./",
      builtin: ['*'],
    },
  });

  const signature = vm.run(codeSnippet);

But i keep getting this error

/node_modules/vm2/lib/resolver-compat.js:34
        return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
XmiliaH commented 2 years ago

This is causes by the wrong usage of the require.external option. From the docs: Values can be true, an array of allowed external modules, or an object (default: false). You should either use external: true or external: []. The first allows to load any modules, the second one only files from the current module and no other modules.