Using Linux, I can run a Javascript file with node file.js. Is it possible to run file.js after entering the Node CLI using node?
2 Answers
You can't really do this.
What you can do is use require and you can make your file behave differently whether it is running standalone or used by require, which gives you almost what you are looking for.
From the CLI:
mod = require("my_module);
mod.my_function();
To figure if you are running standalone, use a test like this: require.main === module
So file.js becomes:
function my_function() {
...
}
exports.my_function = my_function;
if (require.main === module) {
// I'm running standalone
my_function();
}
execit again from the Node repl or use thevmmodule in Node core: nodejs.org/api/vm.html