Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is use of require('.') in node.js

I was reading a node.js cli module documentation and it has one line like this. I know that we can include external modules like this but dont know what is the use of '.' while requiring a module;

const foo = require('.');

Can anyone tell me what is use of it or why its used that way.

like image 916
Manish Saraan Avatar asked Feb 28 '18 13:02

Manish Saraan


People also ask

Why is require () used in NodeJS?

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

How do you define require in NodeJS?

You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).

Why we use require in js?

The require() method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node. js application, you can simply use the require() method.

Is require is a module in NodeJS?

js require Module. Each JavaScript file is treated as a separate module in NodeJS. It uses commonJS module system : require(), exports and module.


2 Answers

It will import index file in the folder where you are running your file will empty require statement. Javascript require module will try to find index.js file if you do not specify any file name(only provide folder reference) in the require() argument.

Basically it's an alias for const foo = require('./index.js');

index.js

module.exports = 1;

foo.js

const foo = require('.');
console.log({ foo });

If both files are in the same folder then it will print

{ foo: 1 }
like image 177
Ridham Tarpara Avatar answered Oct 24 '22 19:10

Ridham Tarpara


In require('.'), '.' represent the current directory, and ".." means parent directory.

-- parent 
  -- child1
    -- grandchild1
    -- grandchild2
  -- child2

Now, suppose you are at child1 and want to import files from grandchild1 or inside the subfolder, Then you have to start from the current location (".") to the grandchild location.

require('./grandchild1/filename')

and, if need to import from the parent or outside your current directory, then you have to start backward that is from parent location (".."):

require('../parent/filename') 
// here '..' take you one folder back (parent folder) and if you want to go one more folder back (parent of parent folder) then add one more pair of dots : '../../some_folder'
like image 34
Himanshu Shekhar Avatar answered Oct 24 '22 18:10

Himanshu Shekhar