[Web] Node.js - module exports
Node.js use 'require()' function to call module.
require('path of directory')
For example, let's say there are two files called 'num.js' and 'sum.js'.
//num.js
var n = 10;
//sum.js
console.log(n);
When you execute this sum.js the error will be occured.
Because in scope of sum.js, 'num1' and 'num2' is not defined.
So let's use 'require()' to call num.js module.
//sum.js
var num = require('../num.js'); //path of num.js
console.log(n);
But still same problem occurs.
It's because variable 'n' is not 'exports'.
//num.js
var n = 10;
exports.n = n;
Then 'sum.js' is executed without any errors.
In 'JavaScript', the base language of 'node.js', there are two different ways of calling module.
One is 'exports' and the other is 'module.exports'.
'require()' is a complicated function, but it can be simplified like this.
var require = function(src){ //line 1
var fileAsStr = readFile(src); //line 2
var module.exports = {}; //line 3
eval(fileAsStr); //line 4
return module.exports; //line 5
};
It's same as..
var require = function(src){ //line 1
var fileAsStr = readFile(src); //line 2
var module.exports = {}; //line 3
const a = 10; //line 4.1
exports.a = a; //line 4.2
return module.exports; //line 5
};
according to..
https://nodejs.sideeffect.kr/docs/v0.10.7/api/modules.html#modules_file_modules
- In line 2, read source and save at 'fileAsStr'.
- In line 3, make an empty hash called 'module.exports'.
- In line 4, eval to 'fileAsStr'. This progress can be said like copying 'src'.
- In line 5, returns the exports hash as an output.
The difference between 'exports' and 'module.exports'
exports
A reference to the 'module.exports' that is shorter to type. See the section about the exports shortcut for details on when to use 'exports' and when to use 'module.exports'.
Copyright by Node.js v10.6.0 Documentation All rights reserved.
As you can see it's not a big deal.
So to avoid errors like the beginning, you have to learn many cases of 'exports' and 'module.exports' usage.