Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to pass object into vm, execute object functions and return it back? #358

Closed
1bye opened this issue Jul 12, 2023 · 1 comment
Closed

Comments

@1bye
Copy link

1bye commented Jul 12, 2023

Hello! I'm glad using this awesome library. I'm currently trying to migrate from vm2 to isolated-vm, and I'm having trouble understanding how to pass an object to the VM. Here's an example object that I want to work with:

{
  status: 'Not Worked',
  changeStatus(status) {
     this.status = status;
  }
}

I would like to execute some code like ( () => { app.changeStatus('Worked') } )(); and retrieve the object with the changed value { status: 'Worked' }. Could you please help me understand how to achieve this using isolated-vm?

I've tried this, but unfortunately this don't work:

const isolate = new ivm.Isolate({ memoryLimit: 8 /* MB */ });

const _code = `(() => { app.changeStatus('Worked') })()`;
const script = await isolate.compileScript(_code)
const context = await isolate.createContext();

const app = { status: 'Not worked', changeStatus(status) {this.status = status} };

await context.global.set('app', app);

return script.runSync(context);

Thanks!

@mklinke
Copy link

mklinke commented Jul 19, 2023

I've just started looking into the migration from vm2 to isolated-vm, too. Take a look into this comment for some information that helped me proceed with my POC.

TL;DR: The integration between isolates is (a little) more effort than with vm2 and you have to think about references, copies and which code executes where. If you don't need side effects (I/O), you may get away with adding the code to the global context of the new isolate itself. However, if you want to allow the isolated code to use side effects, you can create a reference to a function that you have to call in a specific way. See the linked comment for more details.

HTH and good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants