Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if we pass a directory location to Node.js require function?

I have cloned Express.js repo containing an Examples folder having Express.js different use cases. I opened the Hello World example and the code started with the following line

var express = require('../../');

I understand rest of the code in that file, but the line above is going over my head? I know require function is used to include a JS module in your project and one is supposed to pass the module name as argument to require() function, but in the case of the above statement, we are passing in a directory, what is it going to do?

like image 398
segmentationfaulter Avatar asked Mar 14 '23 16:03

segmentationfaulter


2 Answers

You are passing an index.js file that is located two folders after the current one.

Example:

enter image description here

So, if you have this on your yourFile.js

var something = require('../../');

You are making reference to your index.js.

It is exactly the same if you do something like this:

var something = require('../../index');

and both are exactly the same with this one (with .js, which is unnecessary in this case)

var something = require('../../index.js');

That happens because index.js is the default name.

You could read more at nodejs.org but the important part is quoted here:

If there is no package.json file present in the directory, then Node.js will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the above example, then require('./some-library') would attempt to load:

./some-library/index.js

./some-library/index.node

like image 199
Gepser Hoil Avatar answered Apr 07 '23 06:04

Gepser Hoil


It will load index.js if no filename is given.

like image 26
Dave Newton Avatar answered Apr 07 '23 05:04

Dave Newton