Does Node run all the code inside required modules?

后端 未结 4 1527
清酒与你
清酒与你 2021-02-18 23:55

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

相关标签:
4条回答
  • 2021-02-19 00:35

    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..
    
    0 讨论(0)
  • 2021-02-19 00:36

    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.

    0 讨论(0)
  • 2021-02-19 00:53

    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.

    0 讨论(0)
  • 2021-02-19 00:57

    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
    })();
    
    0 讨论(0)
提交回复
热议问题