What happens exported member’s value changed after require() function called (NodeJS)?

Recently I’ am studying ‘NodeJs Module System (CommonJS)’, and found something weird about require() function. First, Let’s look at sample code, ‘exporter.js’

var c;
module.exports= c ;

c = {
    c_key1: 100
};
c .c_key1=0;

As you can see, module.exports=c statement appears before reassignment to variable c. So I guessed if I import module.exports on ‘test.js’ and refer to c_key1 , there would be reference error!! Here is ‘test.js’

const exporter = require('./exporter.js');
console.log(exporter.c_key1);

And as I said, there was reference error.

console.log(exporter.c_key1);
                     ^

TypeError: Cannot read property 'c_key1' of undefined
    at Object.<anonymous> (C:Javascript-WorkspaceJSGrammartest.js:2:22)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

And, I tested example with another ‘exporter.js’ (as below…).

var c;
c = {
    c_key1: 100
};
module.exports= c ;
c .c_key1=0;

And because of 1st example, this time, I also guessed if I refer to c_key1 in ‘test.js’, it would return value of 100 (no 0…).But, result in ‘test.js’ says like below…

0

Ummmm, I can’t understand. I thought statements only before the assignment to module.exports is valid. But 2nd example seems to say it isn’t… Can you tell me what is correct answer??

Answer

Both behaviours are correct.

The below code does not do what you think it does:

var c;
module.exports= c ;

c = {
    c_key1: 100
};
c .c_key1=0;

When you do c = {... you do not re-assign the exported value. The exported value has already been exported as undefined.

It’s kind of like this:

var n;
var m = n;
n = 0;
console.log(m); // m is still undefined