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.
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.
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).
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.
js require Module. Each JavaScript file is treated as a separate module in NodeJS. It uses commonJS module system : require(), exports and module.
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 }
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With