node icon indicating copy to clipboard operation
node copied to clipboard

Don't resolve symlinks when requiring

Open VanCoding opened this issue 11 years ago • 204 comments

Currently, Node.js resolves symlinks when requiring and then uses the real location of the package/file as its __filename and __dirname instead of the symlinked one.

This is a problem because symlinked modules don't act the same as locally copied modules.

For example:

app
    index.js //require("dep1")
    node_modules
        dep1
            index.js //require("dep2")
        dep2
            index.js //console.log('fun!'):

works, but

app
    index.js //require("dep1")
    node_modules
        dep1 -> ../../dep1
        dep2
            index.js
dep1
    index.js //require("dep2")

does not, because dep1 does not act like it's located in the node_modules directory of module and thus cannot find dep2.

This is especially a problem when one wants to symlink modules that have peer-dependencies.

Therefore, I suggest changing the behavior to no longer resolve symlinks. What do you think?

VanCoding avatar Oct 16 '15 12:10 VanCoding

I also found this require/symlink behavior to be unexpected and undesirable. It goes against common UNIX practice.

Out of curiosity - does node on Windows also have this require/symlink behavior? (At one time Windows did not support symlinks). If node behavior on UNIX and Windows differ in this regard that would strengthen to case against symlink resolving in require() on UNIX to be consistent.

At the very least an optional node command line flag could be introduced to disable resolving symlinks when require()ing.

kzc avatar Nov 03 '15 03:11 kzc

@kzc,

Out of curiosity - does node on Windows also have this require/symlink behavior?

Assuming that fs.realPathSync dereferences symlinks on windows then it seems so (but I only checked quickly): https://github.com/nodejs/node/blob/master/lib/module.js#L150

It looks like the problem is that no distinction is made between loading a module with an identifier that starts with '/', '../', or './' and one that doesn't -- all are given the realpath treatment (and it doesn't matter which OS you're using). If, instead, realpath were only used in the former cases, then symlinks would be treated like other files (I think) and you'd get the expected behavior and the ability to localize dependencies for symlink'd modules.

dlongley avatar Nov 03 '15 03:11 dlongley

Regardless of whether require()d modules have relative or absolute paths they still could be converted to canonicalized absolute paths without resolving symlinks. I see the need for the module cache to use absolute paths so that it knows when it's dealing with the same module referenced from various different relative paths. But if someone explicitly introduces a symlink in the path of a module then I'd argue that most would expect it to be treated differently than the symlink resolved version according to its non-resolved directory position.

kzc avatar Nov 03 '15 04:11 kzc

@kzc,

Regardless of whether require()d modules have relative or absolute paths they still could be converted to canonicalized absolute paths without resolving symlinks.

This is problematic for the case shown here: http://grokbase.com/t/gg/nodejs/12cbaygh7a/require-resolving-symlink

This is required because of the way that executables are typically
linked. On Unix, you have something like:

/usr/local/node_modules/foo/bin/foo.js

which does `require("../lib/foo-internals.js")`.

That script is linked to

/usr/local/bin/foo

If we didn't realpath, then it'd be looking for
/usr/local/lib/foo-internals.js instead of
/usr/local/node_modules/foo/lib/foo-internals.js.

dlongley avatar Nov 03 '15 05:11 dlongley

The node start script is a special case that could be symlink resolved if the file has a shebang or a non .js suffix.

kzc avatar Nov 03 '15 07:11 kzc

I'm having the same problem as @fenduru.

  1. Lib installs plugins via npm install, they end up in the correct directory (user project directory).
  2. I also checked require.main.paths[0], it's 100% correct and contains the user project directory.
  3. Nonetheless: require and require.resolve both throw.

This is unexpected.

It only happens when symlinked / npm link'd. In a normal installation everything works as expected. I don't want to npm publish every single change - how am I gonna continue developing the lib?

Since the directory is actually included in require.main.paths this issue is undoubtedly a bug if you ask me. At the very least it's worth fixing.

:+1:

akyoto avatar Nov 10 '15 06:11 akyoto

+1 this is a pain and makes npm link almost useless to me (see https://github.com/npm/npm/issues/5080).

Resolving symlinks this way is just plain wrong and node should not be doing it.

SystemParadox avatar Dec 20 '15 20:12 SystemParadox

In order to fix this issue, it seems node would need to be able to load multiple instances of the same module file (same realpath location).

This means storing symlinked module files in the require.cache using their symlink names instead of their realpath names. There would need to be a new instance in the cache for each module that is loaded via a different path (different symlink) in order to ensure that the proper search paths are used for any require() calls made from within that module. Once this is done, the search path for finding another module could first walk up the symlink path and then, if no match is found, it could walk up the realpath. This might help with backwards compatibility.

However, this seems to be a significant departure from how the require cache currently works. How existing projects would be affected by this is unclear. Though, it may really only affect projects that use peer dependencies -- which are the projects that need this fix. Is a change to fix this unexpected behavior palatable? What do you think, @jasnell?

Is there anyone interested in this issue that feels comfortable enough to create a PR to try and resolve it in a sensible way?

dlongley avatar Dec 29 '15 19:12 dlongley

To summarize the core problem here:

If you want to work on a dependency in the context of a dependent package, you add a node_modules sub-directory to the dependent package and link to its dependency there. Whatever changes you make to the dependency will be reflected in the dependent package.

If you want to work on one of N peer dependencies in the context of a dependent package, you have no such remedy. There is no simple mechanism by which to link to a single peer dependency in the context of the dependent package. This makes developing systems that use peer dependencies unnecessarily difficult.

If we change the module search path behavior to walk up looking for <parent>/node_modules using the symlink path first and then the real path, this problem would be eliminated. Developers of projects that do not use peer dependencies but want to ensure the proper dependencies are loaded, may continue to use the current behavior of adding a node_modules sub-directory. This is how dependency conflicts were already resolved in existing projects.

The non-peer dependency use case that would change would be the following:

A dependent package required a non-peer dependency that was symlinked. That dependency did not have all of its sub-dependencies in a local node_modules sub-directory. Therefore, its realpath parent directories were walked looking for the sub-dependency in <parent>/node_modules until it was found. With this new behavior, its symlink path parent directories would be walked first, prior to walking its realpath parent directories. This could potentially find a different sub-dependency. The original behavior can be easily restored by adding a local node_modules sub-directory.

The only question is, were packages previously depending on this behavior?

This behavior should not affect any npm installed packages unless they have custom install scripts that create symlinks in this manner (and it seems questionable why this would be done at all). There is a potential for this to affect globally installed and npm linked packages, but only if npm install -g does not ensure all required sub-non-peer-dependencies are installed in a node_modules sub-directory. If it doesn't have this assurance, it could be added in future versions to ensure correct behavior with new versions of node.

dlongley avatar Dec 29 '15 20:12 dlongley

Here's an alternative proposal to resolve this issue that should not impact any packages unless they are already using peer dependencies, and therefore, may not need to be considered a potentially breaking change.

Node could be made aware of "peerDependencies" by checking for this value in package.json:

Suppose we have a package top which depends on two packages framework and plugin, where plugin is symlinked to another directory containing a development version of plugin:

|--top
   |--node_modules
     |--framework
     |--plugin (symlink to /dev/plugin)
|--dev
   |--plugin
      |--package.json ({"peerDependencies": {"framework": "^1.0.0"}})
   |--framework

In this scenario, we want top to load plugin from the dev directory and we want plugin to load top/framework not dev/framework.

The plugin package includes a peerDependencies entry in its package.json that has framework as a key. When the top script calls require('plugin'), node finds plugin via its normal mechanism. However, when loading plugin, node sees its package.json file and that it has a peerDependencies entry. This causes plugin to be identified via its absolute path (which may be a symlink) instead of its realpath. From an implementation perspective, an entry in require.cache uses the absolute path as the key and a new module instance as the value (unless previously cached from the absolute path).

Now, when the plugin script calls require('framework'), since framework is in the peerDependencies entry in package.json, it will be be searched for by first walking plugin's module.parent (which will be top's path) before walking its realpath. Any other require target (not present in peerDependencies would be searched for using the module's realpath as usual.

I believe this approach would handle the use case at hand (developing packages that use peer dependencies and using npm link with peer dependencies) without affecting any other packages.

Does anyone here have feedback on this proposal? Would people prefer this one over the previous one -- or neither? General thoughts?

dlongley avatar Dec 29 '15 21:12 dlongley

I really don't think node should be looking in package.json and doing special things with peerDependencies. It should work as expected for any symlinked package. There is no need to special case peerDependencies if node ceases to mess around with resolving symlinks.

I don't see the need to walk up the realpath at all and I would suggest that (excepting any case for backwards compatibility, possibly temporarily) this should be avoided if possible.

Consider:

A
A/node_modules/B (symlink to B)
A/node_modules/C
B
  • require('C') from A should use A/node_modules/C
  • require('C') from B should use B/node_modules/C if available, and fallback to A/node_modules/C (this does not happen at the moment)

Why would you _ever_ want to start searching in A/B's parent?

Even if you think about linking sub-dependencies:

A
A/node_modules/B/node_modules/C (symlink to C)
C

Searching the realpath still makes absolutely no sense - that would mean searching A/C's parent.

The only possible scenario I can think of where searching the realpath would be necessary would be to link to a dependency which is halfway down someone else's tree:

A
A/node_modules/D (symlink to B/node_modules/D???)
B/node_modules/C
B/node_modules/D

...which makes no sense whatsoever. Why would you do this!?!?

So, never resolve symlinks ever, always use the virtual path and don't do anything special.

SystemParadox avatar Dec 31 '15 23:12 SystemParadox

I'd be interested if someone could make a patch for this (even if imperfect) so we could go about testing it. I also think we could get someone to help whoever is interested, if necessary. :)

Fishrock123 avatar Jan 04 '16 20:01 Fishrock123

Related issue:

[rfc] module: change load order #4595

kzc avatar Jan 08 '16 23:01 kzc

I agree 100% with @SystemParadox, I see no reason what so ever to resolve the symlink. Links are supposed to help development by simulating a classic node environment and still be able to make changes easily. If changing this affects anyone it most likely is only in local environment using crazy hacks because of this behavior. You can't write a module assuming your parent or dependencies are at a different "real" location since you don't have any control on the file structure when your module is being installed on another machine. Plus you most likely can't write any code that will create symlinks since you can't assume you are even allowed to (Creating symlinks are disabled for users on Windows by default). Plus, I still fail to see a use case where the current behavior is desirable or even used anywhere at the moment. The only thing I see are people trying very hard to circumvention this bad behavior in node to be able to work with symlink. Sometimes, I had to resolve to copy my module to the final destination and develop directly there so I could test it.

I created an issue a long time ago at nodejs/node-v0.x-archive/issues/18203 and I think I will repost the issue here since this is where the discussion is.

I have been working for a while with link to develop multiple module or simply reuse my local version. However, every time I link a module using peerDependencies the link just becomes very painful.

For instance, if I have a structure like

[email protected] D:\temp\pkg1
├── [email protected]
└── [email protected] -> D:\temp\pkg2

And for whatever reason pkg2 tries to require lodash then I get the error Error: Cannot find module 'lodash'. However, without the link, it works perfectly. An even greater problem is if I happened to have lodash installed globally it works with the link, but not using the version intended because I could have version 2.8.0 installed globally. This is worst, because you don't get an error, everything runs and at one point it might break and you will have to search everywhere to finally realise you were not using the right version because of your link.

Now I wanted to try to find the source of the problem and maybe fix it. I realized that when you require pkg2 in my example, its path will be D:\temp\pkg2\index.js instead of D:\temp\pkg1\node_modules\pkg2\index.js which result in the resolve paths to be

paths: Array[3]
0: "D:\temp\pkg2\node_modules"
1: "D:\temp\node_modules"
2: "D:\node_modules"

Instead of

paths: Array[4]
0: "D:\temp\pkg1\node_modules\pkg2\node_modules"
1: "D:\temp\pkg1\node_modules"
2: "D:\temp\node_modules"
3: "D:\node_modules"

I tried to change the function tryFile in module.js as follow

// check if the file exists and is not a directory
function tryFile(requestPath) {
  var fs = NativeModule.require('fs');
  var stats = statPath(requestPath);
  if (stats && !stats.isDirectory()) {
    return requestPath; // <= Fix: use the symlink directly
    //return fs.realpathSync(requestPath, Module._realpathCache);
  }
  return false;
}

And this was the extend of the change required to fix the issue

Cellule avatar Jan 24 '16 10:01 Cellule

Instead of using fs.realpathSync() for module require resolution, it ought be normalized with path.resolve() which returns an absolute canonical path without resolving symlinks.

Conceptually it would better to have something like this patch against node-v5.5.0:

--- lib/module.js.orig  2016-01-24 12:25:44.000000000 -0500
+++ lib/module.js   2016-01-24 12:41:44.000000000 -0500
@@ -123,7 +123,7 @@
 }

 function toRealPath(requestPath) {
-  return fs.realpathSync(requestPath, Module._realpathCache);
+  return path.resolve(requestPath);
 }

 // given a path check a the file exists with any of the set extensions
@@ -287,6 +287,7 @@
     debug('Module._load REQUEST %s parent: %s', request, parent.id);
   }

+  if (isMain) request = fs.realpathSync(request);
   var filename = Module._resolveFilename(request, parent);

   var cachedModule = Module._cache[filename];

The sole place where resolving symlinks is necessary is if the node start script happens to be a symlink - see isMain above.

Of course lstat data would have to be cached through some other means since Module._realpathCache would no longer be used. Patch above did not address that implementation detail.

kzc avatar Jan 24 '16 18:01 kzc

@VanCoding

The only real problem that i see is when a module gets required multiple times through different symlinks it would not be cached by npm and get loaded multiple times.

Yes, caching is a real problem. Currently, you could just symbol link all deps to a global store because they share the same cache. Though npm doesn't do that but theroically someone could create a package manager use such method. See: https://nodejs.org/dist/latest-v5.x/docs/api/modules.html#modules_addenda_package_manager_tips

hax avatar Mar 29 '16 14:03 hax

I created a PR for this issue here: https://github.com/nodejs/node/pull/5950

Passes all of Canary in the Gold Mine on linux and windows, things are looking pretty good as far as stability goes. W/R/T caching, modules still get cached, just according to their canonical symbolic path -- I'd argue that modules should never get cached according to their realpath because then we're just back to fighting the symbolic path abstractions that the filesystem gives us.

lamara avatar Mar 30 '16 04:03 lamara

I think this issue can be closed out now.

dlongley avatar Apr 27 '16 02:04 dlongley

Done!

jasnell avatar Apr 27 '16 02:04 jasnell

Unfortunately, just like my previous comment metioned, it may break the cache behavior of alternative package managers. And I tested ied, pnpm, npminstall under Node V6 today. All those alternative package installers are rely on the original symbol link behavior and now they all lose cache in Node V6! That means if you install babel6 with these tools, you will suffer from performance issue same as babel6 in npm2. 😭

@jasnell I suggest revert this PR before we found the solution.

cc the authors of ied @alexanderGugel , pnpm @rstacruz, npminstall @fengmk2 and @dead-horse

hax avatar Apr 27 '16 10:04 hax