Does Node run all the code inside required modules?

蹲街弑〆低调 提交于 2020-01-13 07:46:13

问题


Are node modules run when they are required?

For example: You have a file foo.js that contains some code and some exports.

When I import the file by running the following code

var foo = require(./foo.js);

is all the code inside the file foo.js run and only exported after that?


回答1:


Much like in a browser's <script>, as soon as you require a module the code is parsed and executed.

However, depending on how the module's code is structured, there may be no function calls.

For example:

// my-module-1.js
// This one only defines a function.
// Nothing happens until you call it.
function doSomething () {
    // body
}
module.exports = doSomething;


// my-module-2.js
// This one will actually call the anonymous
// function as soon as you `require` it.
(function () {
    // body
})();



回答2:


Some examples..

'use strict';
var a = 2 * 4;  //this is executed when require called
console.log('required'); //so is this..    
function doSomething() {};  //this is just parsed
module.exports = doSomething;  //this is placed on the exports, but still not executed..



回答3:


Only in the sense that any other JS code is run when loaded.

e.g. a function definition in the main body of the module will be run and create a function, but that function won't be called until some other code actually calls it.




回答4:


Before exporting the content that are visible outside of your module, if there is same code that can be execute it it execute but the content that are export like a class will be execute in the code that import it.

For example, if I have this code

console.log("foo.js")
module.exports = {
     Person: function(){}   
} 

the console.log will be execute when you require it.



来源:https://stackoverflow.com/questions/40464552/does-node-run-all-the-code-inside-required-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!