Node.js requires without storing it in a variable

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

"use strict"; require('chromedriver'); var selenium = require('selenium-webdriver'); var driver = new selenium.Builder() .forBrowser('chrome') .build(); 

What I do not understand is the line:

require('chromedriver');

If I delete it, I get an error message:

 Error: The ChromeDriver could not be found on the current PATH. Please download the latest version of the ChromeDriver from http://chromedriver.storage.googleapis.com/index.html and ensure it can be found on your PATH. 

And so it does.

I understand what var chromedriver = require('chromedriver'); , and I only saw that the require function is still used.

So my questions regarding the string are: require('chromedriver');

Why does it work?

Where is the required chrome recorder located?

What happens in genereal if the require () function does not save its return to a variable?

+6
source share
3 answers

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

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

in the .js file and then require this file in the node program, you will get 100 lines added to the console and nothing else will happen.

+8
source

The basic thing to require is that it executes code written in a module. In the end, this executable code may or may not have returned something. In your case, it does not matter what this code returns, but what matters is that this code is executed at least once.

It is also important to note that the result of require cached. This means that even if you need this module several times, the "code" will be executed only once.

This whole paradigm of modules also requires a CommonJS template, I suggest you read it.

+13
source

A module may not export anything, but instead it may assign some global things.

For example, in helper.js

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

and in main.js

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

Some people may not like this because you will pollute the global namespace. But for small applications, you can get away with it.

0
source

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


All Articles