Prashant Agrawal
Prashant Agrawal

Reputation: 670

How to execute user submitted javascript code in sandbox environment in node?

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.

Upvotes: 0

Views: 394

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123443

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()

Upvotes: 1

Related Questions