Reputation: 840
I would like to execute an JS file passed in argument in my NodeJS app (without require each others)
Example :
$ node myapp test.js
test.js
console.log("Do some work")
test();
myapp.js
var test = function(){ console.log("Test working");
here_execute_js_in_process.argv[2]();
I tried the simplest option, read file thanks to fs.readFile and eval resulted data :
fs.readFile(script, function(err,data){
if(err) console.log(err);
eval(data);
});
but didn't worked, have you got a any solution ?
Upvotes: 0
Views: 1005
Reputation: 1669
Test.js is good as is.
Slightly-modified myapp.js:
var fs = require('fs');
function include(inc) {
eval(fs.readFileSync(inc, 'utf-8').toString());
}
console.log("Running myapp.js with arg[2]=[%s]", process.argv[2]);
var test = function() { console.log("Test working")};
if (process.argv[2])
include(process.argv[2]);
Upvotes: 1