The scenario
I am planning to develop a small online judge site for hiring purpose, where I can create contests and participants can solve and submit their solutions.
For that I will provide them an online code editor, where they write their codes and submit. After the submission the source code will send to a node server using a POST
request and the source code will send as a string.
Now the problem is how to compile and run the javascript code from string and get the result.
What have I tried
function runCode(code) {
let input = 5;
const wrap = source => `{ return ${source} };`;
const fn = new Function(wrap(code));
const output = fn.call(null).call(null, input); // The output is n * n = 5 * 5 = 25
console.log(output);
}
runCode(`function myFunction(n) { return n * n; }`);
What am I seeking for-
The code is working perfectly, but I don't understand is this a good way to implement the scenario? Is there any other better & secure way? I've heard about the node
's vm
package.