tuchk4 / magic-require

Correct node require function (according to caller dirname and current cwd) for linked (npm link) or global packages
5 stars 0 forks source link

Cannot identify global module with nvm #1

Open d6u opened 8 years ago

d6u commented 8 years ago

Appreciate the work of this module. But seems like it doesn't work with nvm. I'm using OS X.

$ nvm --version
0.30.1

$ ll /Users/<user_name>/.nvm/versions/node/v4.2.4/lib/node_modules/
drwxr-xr-x 25 daiwei staff 850 Jan 13 11:39 npm/
drwxr-xr-x 14 daiwei staff 476 Jan 25 16:38 npm-check-updates/

$ node
> var m = require('magic-require');
> m.resolve('npm');
null
> m.isExists('npm-check-updates');
false
tuchk4 commented 8 years ago

@d6u Thx for reporting. I will check it ASAP

tuchk4 commented 8 years ago

@d6u Could you please run this function and comment its output?

// test.js
var exec = require('child_process').execSync;
var join = require('path').join;
var relative = require('path').relative;

function magic(id) {
    var stdout = exec('npm prefix -g');

    console.log(stdout.toString());

    var path = join(stdout.toString().trim(), 'lib', 'node_modules', id);
    var relativePath = relative(__dirname, path);

    console.log(path);
    console.log(relativePath);

    console.log(require.resolve(relativePath));
  }

magic('npm');

node test.js

tuchk4 commented 8 years ago

@d6u It is possible to require global modules but it is not a good idea and it is not safe.

The main goal of this package: - require local node_modules (process.cwd() + /node_moduels/) from global context. ({prefix}/lib/node_modules). Prefix could be checked vianpm prefix -gornpm config get prefix`).

Module will be global - if it was installed with -g flag (npm install -g %module_name%) or linked (npm link)

d6u commented 8 years ago
$ node test.js
/Users/daiwei/.nvm/versions/node/v4.2.4

/Users/daiwei/.nvm/versions/node/v4.2.4/lib/node_modules/npm
../../../.nvm/versions/node/v4.2.4/lib/node_modules/npm
/Users/daiwei/.nvm/versions/node/v4.2.4/lib/node_modules/npm/lib/npm.js
d6u commented 8 years ago

I have a valid use case for it https://github.com/d6u/web-playground/issues/19 :smiley:

Are you planning to use npm prefix -g to look up the directory? I noticed you are using execSync, and I know it's important to make the entire process sync because CommonJS is sync. But do you want to provide async API? If so I can create a PR if you don't have time.

pateketrueke commented 8 years ago

+1

I also want this feature if possible...

@tuchk4 why it could be unsafe? BTW, npm root -g seems more suitable than npm prefix -g I guess.