javascript - How to get NodeJS to evaluate multiple traditional JS files -
we using nodejs js engine evaluate student scripts on server side can test correctness.
is there way can 'require' or 'import' multiple traditional .js files? need include submissions multiple users. or i'd have concatenate files?
yes, node.js (like high level languages) supports dynamic import. if have list of files, example
var files = ["student1.js", "student2.js", "student3.js", ...];
then can do
files.foreach(function(f) { try { require(f); } catch(e) { console.log("error in file: "+f); } });
this automatically import , evaluate these files. note might throw exception (because of errors in files),so that's why wrapped try{}catch{}
.
however if keep scripts in database , in node.js have them strings use eval:
var scripts = ["var x = 1;", "console.log('test');", ...]; scripts.foreach(function(s) { try { eval(s); } catch(e) { console.log("error in script:\n"+s); } });
of course "traditional" (i assume mean browser-side javascript) scripts may not compatibile node.js (for example there no window
in node.js).
warning: note both methods unsafe (users can upload malicious scripts), perhaps best idea spawn separate node.js process (in restricted environment) each 1 of them. write script well, it's bit more complicated.
Comments
Post a Comment