0

So what I am trying to do is as take a javascript code as input from user and return him the result. Right now I am executing the code submitted by user just using eval (with some safety checks). But I understand this is highly unreliable. So what I want to achieve is run this in sandbox environment safely and return the result to user. E.g

Input:

var a =[1,2,3];
a.map(n => n*2);

Output:

[2,4,6]

I tried using vm in node but I don't really understand how to get the final result from it.

1 Answer 1

1

I tried using vm in node but I don't really understand how to get the final result from it.

Many vm module functions, like vm.runInNewContext(), will return the result of the last statement in the string, similar to eval().

var vm = require('vm');
var script = 'var a = [1, 2, 3]; a.map(n => n * 2);';

var sandbox = {};
var result = vm.runInNewContext(script, sandbox);

console.log(sandbox); // { a: [1, 2, 3] }
console.log(result);  // [2, 4, 6]

An example of capturing the result is given in the description for vm.runInThisContext()

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @jonathan. It worked. Is it possible to run this in a separate process. I mean how would you advice to handle case like "while (true) {}"
@PrashantAgrawal To run it as a separate process, you'll have to use the child_process module. If you can save the user's input to a file, then it can be run with child_process.fork(). To receive the result, you can require the script to .send() it – how to send message to parent process
How to use Node VM with source maps?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.