Confusion regarding the behavior of Node.js when a file requires a module with nothing exported

I have a general and high-level understanding of the functionality and nature of Node.js' require()and module.exports. However, there are some behaviors that do not make sense to me.

Let's say I have two very simple single-line files a.jsand b.js.

In a.js:

require('./b.js');

and in b.js:

console.log("testing");

and if I run node a.jsin the terminal, here is what is written:

$ node a.js
testing.

which means that only requiring a file / module, the requested content of the file is exposed to the file that issues the request (, right?)


Now I am changing a.jsas follows:

require('./b.js');
testFunc(1, 2);

and b.js:

var testFunc = function(a, b) {
    var result = a + b;
    return result;
}

and run again node a.jsin terminal:

$ node a.js
/demo/a.js:3
testFunc(1, 2);
^

ReferenceError: testFunc is not defined
......

, ? -, , b.js, a.js b.js. , b.js, , ReferenceError: testFunc is not defined. ?

, require() script, ? module.exports?

+4
3

.

" , " , module.exports ".

Node , .

(function (exports, require, module, __filename, __dirname) {
// Your module code actually lives in here
});

, , .

, console.log() . , iframe , iframe .

console.log("whoa");
Hide result
+2

a.js. nodejs .

, , , , . , console.log.

- b.js, - :

module.exports = {
  testFunc: testFunc
}

a.js

var b = require('./b.js')
b.testFunc(1, 2)

, , . , testFunc b testFunc nodejs , testFunc.

+1

.

script Node JS (b.js ), , - , , script .

:

a.js

'use strict';

    let b = require('./b.js');

    let result = b.testFunc(1, 4);
    console.log(result);

b.js

'use strict';

    module.exports.testFunc = function(a, b) {
        let result = a + b;
        return result;
    }

    console.log(this.testFunc(5,5));
+1
source

Source: https://habr.com/ru/post/1648445/


All Articles