简体   繁体   中英

Node.js: require in REPL?

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:

  • You can provide the useGlobal: true option in your call to start .
  • You can attach external objects to the REPL's 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM