I have a script foo.js
that contains some functions I want to play with in the REPL.
Is there a way to have node execute my script and then jump into a
replpad
is cool, but for a quick and easy way to load a file into node, import its variables and start a repl, you can add the following code to the end of your .js file
if (require.main === module){
(function() {
var _context = require('repl').start({prompt: '$> '}).context;
var scope = require('lexical-scope')(require('fs').readFileSync(__filename));
for (var name in scope.locals[''] )
_context[scope.locals[''][name]] = eval(scope.locals[''][name]);
for (name in scope.globals.exported)
_context[scope.globals.exported[name]] = eval(scope.globals.exported[name]);
})();
}
Now if your file is src.js
, running node src.js
will start node, load the file, start a REPL, and copy all the objects declared as var
at the top level as well as any exported globals.
The if (require.main === module)
ensures that this code will not be executed if src.js
is included through a require
statement. I fact, you can add any code you want to be excuted when you are running src.js
standalone for debugging purposes inside the if
statement.