execute some code and then go into interactive node

Is there a way to execute some code (in a file or from a string, doesn't really matter) before dropping into interactive mode in node.js?

For example, if I create a script __preamble__.js which contains:

console.log("preamble executed! poor guy!");

and a user types node __preamble__.js they get this output:

preamble executed! poor guy!
> [interactive mode]

Solution 1:

Really old question but...

I was looking for something similar, I believe, and found out this. You can open the REPL (typing node on your terminal) and then load a file. Like this: .load ./script.js. Press enter and the file content will be executed. Now everything created (object, variable, function) in your script will be available.

For example:

// script.js
var y = {
    name: 'obj',
    status: true
};

var x = setInterval(function () {
    console.log('As time goes by...');
}, 5000);

On the REPL:

//REPL
.load ./script.js

Now you type on the REPL and interact with the "living code". You can console.log(y) or clearInterval(x);

It will be a bit odd, cause "As time goes by..." keep showing up every five seconds (or so). But it will work!

Solution 2:

You can start a new repl in your Node software pretty easily:

var repl = require("repl");
var r = repl.start("node> ");
r.context.pause = pauseHTTP;
r.context.resume = resumeHTTP;

From within the REPL you can then call pause() or resume() and execute the functions pauseHTTP() and resumeHTTP() directly. Just assign whatever you want to expose to the REPL's context member.

Solution 3:

This can be achieved with the current version of NodeJS (5.9.1):

$ node -i -e "console.log('A message')"

The -e flag evaluates the string and the -i flag begins the interactive mode.

You can read more in the referenced pull request

Solution 4:

node -r allows you to require a module when REPL starts up. NODE_PATH sets the module search path. So you can run something like this on your command line:

NODE_PATH=. node -r myscript.js

This should put you in a REPL with your script loaded.