Why require in REPL doesn't use cache from main context and requires file again?
Example: test.js:
var repl = require('repl');
global.a = require('./a');
repl.start({
prompt: "node via stdin> ",
input: process.stdin,
output: process.stdout
});
a.js
console.log(1)
I'm starting test.js:
node test.js
It print's "1"
when i print "require('./a')" in REPL:
node via stdin> var aInREPL = require('./a')
and it prints "1" again, and so, global.a !== aInREPL
But sometimes I need to get in REPL same object as in main program (for example Singletone). How can I do this?
Add the required code (object, function, ..) to the REPL's context:
var repl = require('repl');
repl.start({
prompt: "node via stdin> ",
input: process.stdin,
output: process.stdout
}).context.a = require('./a.js');
Now it will print 1 only once =) or add global to REPL's context
Out of the box the REPL runs in a different context (see repl.start function for details).
Basically, you have two options to share your global context with the newly started REPL:
useGlobal: true
option in your call to start
.context
property.Which way is preferred depends on what you want to achieve: Do you want to share anything, then go with useGlobal
. If you only want to share selected objects, use the context
property and only assign those objects you want to share (see Scott's post for an example).