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

@kzc ...thank you for the clarification :-) ... let's walk through that a bit. Hopefully I understand your intent correctly...

Scenario 1:

myApp
     /index.js
     /node_modules
                  /.module_legacy
                  /baz (@version=1)
                  /foo --> ../../foo
                  /bar
                      /node_modules
                                   /baz (@version=2)
                                   /foo --> ../../../../foo
modules
      /foo
          /node_modules
                       /bar --> ../../../myApp/node_modules/bar

This would have the result of creating multiple instances of foo. The first (at symlink myApp/node_modules/foo) would fail to find it's peer dependency baz (@version=1), while the second find it's peer dependency baz (@version=2). Multiple instances of bar would be created,

Our cache would look something like...

{
  "modules/foo": { },
  "modules/foo/node_modules/bar": { },
  "modules/foo/node_modules/bar/node_modules/foo": { },
  "modules/foo/node_modules/bar/node_modules/baz": { },
  "modules/foo/node_modules/bar/node_modules/foo/node_modules/bar": { },
  ...
  "myApp/node_modules/bar": { },
  "myApp/node_modules/bar/node_modules/foo": { },
  "myApp/node_modules/bar/node_modules/baz": { },
  "myApp/node_modules/bar/node_modules/foo/node_modules/bar": { },
  "myApp/node_modules/bar/node_modules/foo/node_modules/bar/node_modules/foo": { },
  "myApp/node_modules/bar/node_modules/foo/node_modules/bar/node_modules/baz": { },
  ...
}

In other words, all we've done here is combined both problems we're trying to solve :-)

Scenario 2:

myApp
     /index.js
     /node_modules
                  /baz (@version=1)
                  /foo --> ../../foo
                  /bar
                      /node_modules
                                   /.module_legacy
                                   /baz (@version=2)
                                   /foo --> ../../../../foo
modules
      /foo
          /node_modules
                       /bar --> ../../../myApp/node_modules/bar

Again, two instances of foo would be created. One would find it's peer dependency, the other would not. Two instances of bar would be loaded.

Our cache would look something like:

{
  "myApp/node_modules/baz": { },
  "myApp/node_modules/foo": { },
  "myApp/node_modules/foo/node_modules/bar": { },
  "modules/foo": { },
  "modules/foo/node_modules/bar": { },
}

Scenario 3:

myApp
     /index.js
     /node_modules
                  /.module_legacy
                  /baz (@version=1)
                  /foo --> ../../foo
                  /bar
                      /node_modules
                                   /.module_legacy
                                   /baz (@version=2)
                                   /foo --> ../../../../foo
modules
      /foo
          /node_modules
                       /bar --> ../../../myApp/node_modules/bar

Only a single version of foo would be loaded, which would fail to find it's peer dependency. Two instances of bar would be loaded.

Our cache would look something like:

{
  "modules/foo": { },
  "modules/foo/node_modules/bar": { },
  "myApp/node_modules/bar": { }
}

Scenario 4:

myApp
     /index.js
     /node_modules
                  /.module_legacy
                  /baz (@version=1)
                  /foo --> ../../foo
                  /bar
                      /node_modules
                                   /.module_legacy
                                   /baz (@version=2)
                                   /foo --> ../../../../foo
modules
      /foo
          /node_modules
                       /.module_legacy
                       /bar --> ../../../myApp/node_modules/bar

Once instance of foo would be created, that would fail to find it's peer dependency. One instance of bar would be created.

Our cache would look something like:

{
  "modules/foo": { },
  "myApp/node_modules/bar": { }
}

Scenario 5:

myApp
     /index.js
     /node_modules
                  /.module_legacy
                  /baz (@version=1)
                  /foo --> ../../foo
                  /bar
                      /node_modules
                                   /baz (@version=2)
                                   /foo --> ../../../../foo
modules
      /foo
          /node_modules
                       /.module_legacy
                       /bar --> ../../../myApp/node_modules/bar

This is an interesting one... one instance of bar would be created. I think two instances of foo would be created that would each point to the single bar, which points to only one of the foo instances.

Our cache would look something like:

{
  "modules/foo": { },
  "myApp/node_modules/bar": { },
  "myApp/node_modules/bar/node_modules/baz": { },
  "myApp/node_modules/bar/node_modules/foo": { }
}

Scenario 6:

myApp
     /index.js
     /node_modules
                  /baz (@version=1)
                  /foo --> ../../foo
                  /bar
                      /node_modules
                                   /baz (@version=2)
                                   /foo --> ../../../../foo
modules
      /foo
          /node_modules
                       /.module_legacy
                       /bar --> ../../../myApp/node_modules/bar

One instance of bar would be created. Two foo instances that point to bar. The bar would point to one of the instances of foo.

Our cache would look something like:

{
   "myApp/node_modules/baz": { },
   "myApp/node_modules/foo": { },
   "myApp/node_modules/bar": { },
   "myApp/node_modules/bar/node_modules/baz": { },
   "myApp/node_modules/bar/node_modules/foo": { },
}

jasnell avatar Apr 28 '16 02:04 jasnell

@alexanderGugel ... at this point, walking through the various exercises on this, It appears that any scenario where we have both the old and new approaches being used within a single process only makes the problem worse in that we end up with the downsides of both approaches more than it actually solves anything. We need a single behavior, not multiple. It needs to be either (a) Revert to the old behavior, (b) Stick with the new behavior or (c) Find a behavior that works for both.

jasnell avatar Apr 28 '16 02:04 jasnell

@jasnell I think @alexanderGugel's Approach 3 can fix both issues. No need to revert and keep symlink path has a way to use the realpath for require.

fengmk2 avatar Apr 28 '16 02:04 fengmk2

In other words, all we've done here is combined both problems we're trying to solve :-)

@jasnell The old symlink scheme never found the correct peer dependencies. So that legacy "behavior" would be preserved. I'm not suggesting it's an improvement. Hence the push for the newer resolution algorithm. The only way the legacy symlink behavior worked in my experience was in a flat node_modules scenario where every module was at the same level relative to each other.

kzc avatar Apr 28 '16 02:04 kzc

We need a single behavior, not multiple. It needs to be either (a) Revert to the old behavior, (b) Stick with the new behavior or (c) Find a behavior that works for both.

  • @jasnell

We already have both scenarios in there, which is perfectly fine. On isMain, we resolve to the real path, otherwise we use the linkname. Those are exactly the two cases we need to cover.

@jasnell I think @alexanderGugel's Approach 3 can fix both issues. No need to revert and keep symlink path has a way to use the realpath for require.

  • @fengmk2

The suggested change is actually pretty trivial! Instead of using the real path when isMain, we use it if the name filename start with _ (assuming we want to keep things backwards compatible, otherwise it would be the exact other way around: Use the real path only if the name start with _).

@jasnell The old symlink scheme never found the correct peer dependencies. So that legacy "behavior" would be preserved. I'm not suggesting it's an improvement. Hence the push for the newer resolution algorithm. The only way the legacy symlink behavior worked in my experience was in a flat node_modules scenario where every module was at the same level relative to each other.

That's why I'm 👎 on using a the filename + real path as a key for the module cache. It actually combines both issues and that's the solution that introduces an additional strategy (legacy file).

alexanderGugel avatar Apr 28 '16 02:04 alexanderGugel

Hmm... I'm going to remain skeptical until I see a working example ;-) Running through all of the scenarios I'm not seeing a consistent path forward with an implementation that uses both semantics. I'm happy to be proven wrong tho! :-)

jasnell avatar Apr 28 '16 02:04 jasnell

@jasnell PR is on its way :)

alexanderGugel avatar Apr 28 '16 02:04 alexanderGugel

@alexanderGugel You mean _ detection is reversed for main script? It seems weird... Maybe we could make it consistent by only use new behavior if start with _ , and change npm link behavior to always prefix _.

hax avatar Apr 28 '16 02:04 hax

@hax No, there is no prefix detection in there (at least currently not). The "second" strategy I was mentioning referred to the fact that require is currently already using the resolved real path for the first (=main) modules, which is indicated via isMain in module.js.

I'm actually gonna have to go to bed now. I didn't completely get it to work yet, but it should be fairly straightforward (something along those lines).

alexanderGugel avatar Apr 28 '16 03:04 alexanderGugel

+1 to continuing to explore the prefix option in @alexanderGugel's gist.

dlongley avatar Apr 28 '16 03:04 dlongley

The common point of both the prefix and dot file schemes is to add one extra bit of information to a symlink to know whether to realpath it or not. It would be nice keep the symlink name and encode that bit in another way. On Mac it is possible to change the permission bits on the symlink itself which otherwise are not used but I don't think it's true of other OSes. Are there any other unused bits related to symlinks at our disposal that would work on all platforms? Just throwing the idea out there.

kzc avatar Apr 28 '16 04:04 kzc

I see more than a couple of JS files with _ prefixes in node_modules for my projects. lodash is one. And one instance of a directory beginning with _ - node_modules/fbjs/lib/__mocks__

Using the lesser used @ may be a better alternative for a prefix.

kzc avatar Apr 28 '16 05:04 kzc

I don't see adding a prefix as an option. The reason for this is that a lot of modules assume that they can reach their direct dependencies folders under ./node_modules/x

So, if someone has an express app like this:

app.use(express.static("/public/bootstrap","./node_modules/bootstrap/dist/"))

This would no longer work. It would need to require.resolve the module's location first and then path.resolve relative from there. I assume that would affect a lot of modules.

Basically, we're talking about 2 different approaches here:

A) adding the information to the symlink B) adding the information to the module

What @kzc and @alexanderGugel are proposing falls under approach A. The proplem with A is that it is really complicated, and hard to reason about.

Let's assume the following scenario:

/
    a/ -> symlink to ./b, configured to use real path
    b/
        index.js -> symlink to ../b.js, configured to use virtual path
    b.js -> console.log(__filename)
    index.js -> require("./a/index.js");

question: what would the output? /a/index.js? /b/index.js? /b.js?

The problem is, that there can be multiple symlinks in a path, and we would have to walk up the whole path and check if it's a symlink and how it is configured and decide on which configuration has precedence over the other. Not a trivial task.

That's why I proposed doing it with approach B and configure it where the path points to: in the module. That means, if we require a module through different symlinks, we always get the same configuration. But it also means that we can't configure it differently for each symlink.The question is: does it matter? Maybe not.

Let's look at the 3 real world scenarios:

NPM

app/
    node_modules/
        a/
            index.js -> require("b");
            node_modules/
                b/
                     index.js -> require("c"); //peer dependency
        c/
            index.js
    index.js -> require("a"); require("c");

In this scenario, everything works fine in in both the new and the old way, since no symlinks were used.

NPM developing a

app/
    node_modules/
        a/ -> symlink to ../../a_dev
        c/
            index.js
    index.js -> require("a"); require("c");
a_dev/
    index.js -> require("b");
    node_modules/
        b/
            index.js -> require("c"); //peer dependency

In this scenario, everything works fine in in the new way, but did not work in the old way, because b/index.js could not find 'c'.

other package manager

app/
    node_modules/
        a/ -> symlink to ../../a
        c/ -> symlink to ../../c
     index.js -> require("a"); require("c");
a/
    node_modules/
        b/ -> symlink to ../../b
     index.js -> require("b");
     .modules_legacy
b/
    node_modules
        c/ -> symlink to ../..c
    index.js -> require("c"); //peer dependency
    .modules_legacy
c/
    index.js
    .modules_legacy

This had worked in the old way, but does not currently work in the new way. But using .modules_legacy files, we could fix it.

It's important to note, that the .modules_legacy file is nothing a developer would add manually to his module. In fact, a developer shouldn't maybe even know that it exists. The proposed feature would basically be for package-manager exclusive use. So package managers decide on adding the file or not depending on the module hierarchy they build. We should prevent developers from adding a '.modules_legacy' file to their modules manually, because they would no longer work with NPM if they do so.

Yes, we could also just go for the commandline/environment var option but then either NPM users would need to provide it when they're developing the app and a module simultaneously, or users of other package managers would have to provide it every the time they run their application.

VanCoding avatar Apr 28 '16 07:04 VanCoding

I have no :cow: with either of the emerging approaches (_symlink, .modules_legacy or env variable), I'm a :+1: for either one.

The important thing is that the standard resolve strategy is clear and simple.

Adding a fallback hook in either one of those ways is an acceptable corner case that provide great benefits (yay pnpm :heart:) :rocket: Let's just remember to document it well :stuck_out_tongue_winking_eye:

asbjornenge avatar Apr 28 '16 08:04 asbjornenge

@alexanderGugel Example code:

import p from `mod/${process.config.target_defaults.default_configuration}/p`;

In this case I'm attempting to load a native resource (namely p.node) and determine whether it should load the Release or the Debug build based on the build type of node I'm running. Unfortunately es6 modules don't allow runtime path resolution. So I'd have to symlink p.node before running my script, if I didn't want to change my script every time I wanted to switch configurations that is.

This could be pretty easily automated while building, with a small patch. e.g. using a command like ./node_g $(which node-gyp) it could auto detect which configuration of node you're building with and automatically rewrite the symlink.

trevnorris avatar Apr 28 '16 08:04 trevnorris

@VanCoding Yes, under the "other package manager" scenario with a flat node_modules structure the dot file approach at the module level would work as well as legacy resolution did. We're not trying to make the legacy resolution mechanism better than it was, just to preserve its behavior.

In your proposal would the use of .modules_legacy only apply to symlinks of individual javascript files in the same directory as the dot file and any symlinks within the immediate node_modules child directory?

Also, in your example:

c/
    index.js
    .modules_legacy

was .modules_legacy here superfluous? It would still work the same if removed because there are no symlinks present in the immediate directory nor does c/ have a child node_modules directory containing symlinks, correct?

kzc avatar Apr 28 '16 12:04 kzc

What @kzc and @alexanderGugel are proposing falls under approach A.

I was just pointing out that _ as a prefix would not be a good choice due to its widespread use. I prefer a dot file approach or encoding the information within the actual symlink itself somehow instead of its name.

Edit: encoding the legacy realpath behavior bit within the OS symlink itself wouldn't survive tarring and untarring so I withdraw this idea as unworkable.

kzc avatar Apr 28 '16 12:04 kzc

👍 for using _ as a prefix for symlinks that should be resolved according to the old algorithm.

I was just pointing out that _ as a prefix would not be a good choice due to its widespread use.

As @alexanderGugel pointed out above, package names starting with _ aren't valid npm package names. Linking packages is by far the most common use case for using the old mechanism.

@kzc Can you point out a specific use case where a _ prefixed symlink is actually being used to share a node_modules directory located at the real path? I think this should be extremely uncommon.

Also I wouldn't call this "legacy behaviour". I think the above discussion is proof enough that there are legitimate use cases for both approaches.

That being said, prefixing using . also makes sense. . is hidden, so it kind of implies that it behaves differently.

👎 for using a separate file. It's less flexible to enforce this behaviour on a "real" module-by-module basis, rather than per-link.

nowtvicebergteam avatar Apr 28 '16 15:04 nowtvicebergteam

This does affect code completely outside of node_modules as well. And breaks one of the (to my understanding) old and reliable node module system rules: Each file is executed exactly once. Especially given the status of the module system as "locked", that shouldn't be expected (I think).

This file for example:

const bar = require('./bar'); // bar contains an index.js
const foo = require('./foo'); // foo is a symlink to bar
console.log('foo === bar', foo === bar); // expected to be `true`

In node 4 this runs the top-level code in bar/index.js once and in node 6 it will run it multiple times - including any side effects it might have (putting stylistic concerns about top-level side effects aside). Making such a change to a locked part of the API without any deprecation / opt-in period seems weird.

hybrist avatar Apr 28 '16 15:04 hybrist

As @alexanderGugel pointed out above, package names starting with _ aren't valid npm package names. Linking packages is by far the most common use case for using the old mechanism.

@nowtvicebergteam That's fine for package names, but as @jkrems points out what about individual symlinked JS files? They can potentially have _ prefixes.

The dot file approach handles both symlinked files and symlinked directories.

kzc avatar Apr 28 '16 15:04 kzc