user169251 user169251 - 1 year ago 64
Node.js Question

Node.js require() does not look in parent directory when using "npm link"

I'm developing a module for node.js. For development I'm using "npm link" which basically creates a sym link on the drive (I'm running Ubuntu) to the development location of this module.

When I use require to load a module that the parent application has in it's node_modules folder it is not getting loaded. I instead get a "cannot find module x". I set the environment variable NODE_DEBUG to module and found that it is looking "up" only from the physical location on the drive, not from inside the project.

Does anyone have a suggestion for how I fix this? My current solution is to now unfortunately physically copy the module code into my test project as part of the startup script which is not cool!

Personally I think this might be a bug, but I wasn't sure if it was behaving as expected and I was just doing it wrong.

Answer Source

I can understand how you think that it's "contextually where the module exists", but unfortunately npm link <module> just creates a normal symlink under node_modules. From the context of the linked module, it is not aware (and couldn't reasonably know) that it is symlinked to from other directories.

The require behaviour is complex, but essentially it looks up through the parent directories for node_modules directories, which is correct behaviour. The problem you have is the general problem of peer dependencies, which there are a few solutions for. Rather than linking to Module Project, you could put all of your projects inside a node_modules directory

peer dependencies

Node Project can just require from Module Project, and likewise, Module Project can require from Node Project. If they both require from each other then there could be big problems with circular dependencies, so watch out for that.

It might be helpful if you explain exactly what the linked Module Project is looking for.