I have the following directories and files
/path/to/dir1
/path/to/dir1/server.js
/path/to/dir1/package.json
/path/to/dir1/node_modules
/path/to/dir2/moduleA.js
Then I have moduleA.js which starts like this:
var React = require('react');
And my package.json file looks like this:
{
"dependencies": {
"react": "^0.10.0"
}
}
Now from within server.js if I do this:
require('../dir2/moduleA')
It will find moduleA but then in moduleA I have require('react') which actually resides within the same directory of server.js in the node_modules folder. However this location is not searched and I am getting an error
Error: Cannot find module 'react'
I thought one of the locations searched when resolving require statements was the node_modules directory of the currently executing process? Why is this not working?
Node will look for your modules in special folders named node_modules . A node_modules folder can be on the same level as the current file, or higher up in the directory chain. Node will walk up the directory chain, looking through each node_modules until it finds the module you tried to load.
As building blocks of code structure, Node. js modules allow developers to better structure, reuse, and distribute code. A module is a self-contained file or directory of related code, which can be included in your application wherever needed. Modules and the module system are fundamental parts of how Node.
The require function will look for files in the following order. NPM Modules. It will look in the node_modules folder. Local Modules.
From the documentation:
Loading from
node_module
s FoldersIf the module identifier passed to
require()
is not a native module, and does not begin with'/'
,'../'
, or'./'
, then node starts at the parent directory of the current module, and adds/node_modules
, and attempts to load the module from that location.If it is not found there, then it moves to the parent directory, and so on, until the root of the tree is reached.
For example, if the file at
'/home/ry/projects/foo.js'
calledrequire('bar.js')
, then node would look in the following locations, in this order:/home/ry/projects/node_modules/bar.js /home/ry/node_modules/bar.js /home/node_modules/bar.js /node_modules/bar.js
This allows programs to localize their dependencies, so that they do not clash.
I.e. it would look in /path/to/dir2/node_modules
, /path/to/node_modules
, etc, but not in /path/to/dir1/node_modules
.
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