Is there any way to run JavaScript code in an isolated environment with dependencies, similar to Node.js?

819 Views Asked by At

I've tried using the isolated-vm and vm2 libraries to run code in an isolated environment, but I've run into issues where the required packages are not installed in the isolated environment. isolated-vm not support module and vm2 not installing it on isolated enviroment.

Here I tried with vm2 to run script -

import { NodeVM, VMScript } from "vm2";
import { resolve } from "path";
import fs from "fs";

async function runScript(scriptPath, dependencies = []) {
  const scriptSource = fs.readFileSync(scriptPath, "utf8");

  const vm = new NodeVM({
    console: "inherit",
    sandbox: {},
    require: {
      external: true,
      import: dependencies,
    },
  });
  const script = new VMScript(scriptSource);
  const result = await vm.run(script);
  console.log(result);
}

runScript(resolve("./src/discordService.js"), ["discord.js-selfbot-v13"]);

0

There are 0 best solutions below