I am trying to load a custom module ./routes/exchange.js from another module ./routes/socketRouter.js. It throws
module.js:340
throw err;
^
Error: Cannot find module './routes/exchange'
The same call require('./routes/exchange) done from app.js (in the root directory) is successfull!
Is there a limitation that prevent calling require somewhere else than in the app.js?
I already tried many different path such as:
require('./routes/exchange.js'), require('exchange'), require('exchange.js')
Thanks!
require('./exchange')
That will load a module in the same directory as the source module you're requiring from.
require('exchange') would only load the module if it was in the base node_modules directory.
When requiring from customer modules and files, you give the relative path to the file. So with the follow structures
./my-app
app.js
routes/
exchange.js
socketRouter.js
some-folder/
some-file.js
Now when including exchange.js from app.js, you'd use require('./routes/exchange') When including it from socketRouter.js you'd it's in the same folder, so require('./excahnge').
Just for clarity, when wanting to include exchange.js from some-file.js, you'd reference it as require('../routes/exchnage')
(Note, the .js extension is optional when calling it via require, if exchange was a folder, then it would load the index.js file from that folder see http://nodejs.org/api/modules.html#modules_file_modules and http://nodejs.org/api/modules.html#modules_folders_as_modules)