NodeJS REPL: Why is this variable assignment not fulfilled?

Can someone help me understand the following behavior? I would expect that since I can set global f from within this callback, I also have to change it. I don't understand very well how node handles context vs. global in REPL to understand this, and I would appreciate any insight.

Run REPL without useGlobal

 $ cat test.js var repl = require('repl'); repl.start({useGlobal:false}); 

Now try setting f twice in a row:

 $ node test.js > f ReferenceError: f is not defined > setTimeout(function(){f=1;}, 0); > f 1 

It works for the first time ... now try again:

 > setTimeout(function(){f=2;}, 0); > f 1 

Ha!

The first launch installs it; the second does not affect her.

(Setting useGlobal : true I get the expected behavior.)

+4
source share
1 answer

This is because of the Node faulty vim module that runs your code behind the scenes. When you disable useGlobal, this will change the way it runs your code by moving from vm.runInThisContext to vm.runInContext [1]. Essentially, what happens is that it copies all the variables from the specified sandbox object into the real global object object in which it runs your code, executes the code, and then copies everything back. When you use setTimeout, the change is made after everything is copied back. The fault in this lies partially in the module repl [2] and partially in the module vm [3]. I believe that the vm module is planned for overhaul for the next version.

+2
source

All Articles