Node.js require without storing it into a variable

后端 未结 3 1754
忘掉有多难
忘掉有多难 2020-12-31 03:27

I have the following code snippet and it works in its context.

\"use strict\"; 
require(\'chromedriver\');
var selenium = require(\'selenium-webdriver\');
va         


        
相关标签:
3条回答
  • 2020-12-31 04:00

    The basic thing require does is that it executes code written in the module. At the end this executed code might or might not return something. In your case it doesn't matter what this code returns, rather what matters is that this code is executed at least once.

    It is also important to note that the result of require is cached. This means even if you require that module multiple times the "code" would execute only once.

    This whole paradigm of modules and require comes from CommonJS pattern, I would suggest you to read it.

    0 讨论(0)
  • 2020-12-31 04:09

    Calling the require on the module actually executes whatever code is in the module. In most cases, the module exports one or more functions or an object, which you want to store in a variable. But if you were to write something like:

    for (var i = 0;i < 100; i++){
       console.log("I've been called %d times", i);
    }
    

    in a .js file and then require that file in a node program, you'd get 100 lines added to your console and nothing else happening.

    0 讨论(0)
  • 2020-12-31 04:15

    The module might not export anything, but instead it might assign some stuff to global.

    For example, in helper.js

    global.timeout = 5000;
    
    global.sayHello = function(e) {
        console.log('Hello',e);
    }
    

    and in the main.js

    require('./helper.js');
    
    sayHello('fish');
    

    Some people might not like it, because you'll be polluting the global namespace. But for small applications you can get away with it.

    0 讨论(0)
提交回复
热议问题