0

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 ?

Lombric
  • 830
  • 2
  • 11
  • 23
  • In what way didn’t `eval` work? You might want to take a look at [`vm.runInNewContext`](https://nodejs.org/api/vm.html#vm_vm_runinnewcontext_code_sandbox_options), anyway. – Ry- May 25 '15 at 17:57
  • check http://stackoverflow.com/questions/4351521/how-to-pass-command-line-arguments-to-node-js this – Luka Krajnc May 25 '15 at 18:22

1 Answers1

1

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]);
Lombric
  • 830
  • 2
  • 11
  • 23
Michael Blankenship
  • 1,639
  • 10
  • 16