Hoisted local variable masking global variable?

280 views Asked by At

Came across strange behavior in node. I have an emscripten compiled program that I would like to use as a library. emscripten use a variable Module to control runtime behavior, and generates code like ./lib/g.js below. In the browser, Module is properly aliased from the global defined in index.js to the local var in ./lib/g.js. However, in node, this does not seem to be the case. The construct: var Module = Module || {}; wipes out my global Module.

index.js:

global.Module = { name: 'Module' };
var g = require ( './lib/g.js' );

./lib/g.js:

console.log ( 'Module: ', Module );

var Module = Module || {};

Output of node index.js:

Module:  undefined

I assume in g.js, Module is hoisted and dereferenced only in the local scope, masking the global version (in global.Module). Can anyone suggest a work-around?

This problem can be fixed by editing the emscripten produced code to use var Module = global.Module || {}. While this is a possible workaround, I would rather not edit the code generated by emscripten.

2

There are 2 answers

0
Peter Lyons On BEST ANSWER

You might take a look at using rewire

var rewire = require("rewire");
var g = rewire("./lib/g");
g.__set__("Module", {name: "Module"});
1
Peter Lyons On

Can anyone suggest a work-around?

Just remove the var keyword.