Does Node run all the code inside required modules?

11,988

Solution 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
})();

Solution 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..

Solution 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.

Solution 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.

Share:
11,988

Related videos on Youtube

Victorino Machava
Author by

Victorino Machava

Hi! My Name is Victorino Machava. I am a Web Developer.

Updated on September 15, 2022

Comments

  • Victorino Machava
    Victorino Machava over 1 year

    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?

    • adeneo
      adeneo over 7 years
      Define "run"? All the code is parsed and cached when required, but not neccessarely executed.
    • Victorino Machava
      Victorino Machava over 7 years
      @adeneo Well, I actually meant "executed". And from what I understood from most of the answers, the code is also executed.
  • Victorino Machava
    Victorino Machava over 7 years
    What if there is a function call inside that module? Will it be executed when that module is required?
  • Quentin
    Quentin over 7 years
    @Víctor — Depends if it inside a function or not.
  • Turkhan Badalov
    Turkhan Badalov over 3 years
    Also, nodejs runs the module only once even if it is imported in several places