patriksimek / vm2

Advanced vm/sandbox for Node.js
MIT License
3.86k stars 293 forks source link

`SyntaxError: Illegal return statement` error #497

Closed remal closed 1 year ago

remal commented 1 year ago
const content = 'any text'
const vm = new VM({
    sandbox: {
        content,
    },
    allowAsync: false,
    eval: false,
    wasm: false,
})
const transformedContent = vm.run('return content.replace(/a/, 'b')')

This code fails with SyntaxError: Illegal return statement error. How can it be fixed/rewritten?

XmiliaH commented 1 year ago

Just remove the return.

remal commented 1 year ago

But what if I have a much more complex code with conditions?

XmiliaH commented 1 year ago

The value from the last expression is returned. You could also use a function and immediately call it.

(function(){
return something;
})()
remal commented 1 year ago

@XmiliaH it works, thanks! The issue can be closed.

I think it would be great if this scenario were documented somewhere. What do you think?

XmiliaH commented 1 year ago

I would argue that it already is documented. From the README:

You can also retrieve values from VM.

let number = vm.run('1337'); // returns 1337

But feel free do make a PR.

remal commented 1 year ago

@XmiliaH you're absolutely right - it is documented. However, it's a bit confusing why return doesn't work.

XmiliaH commented 1 year ago

Since the JavaScript top-level scope cannot use the return statement. It is the same for the node vm module.