Dan Tao
Dan Tao

Reputation: 128447

Can I access locally-installed packages from a globally-installed package?

I don't know if I've worded the question properly, so I apologize if it isn't clear from the title what I mean.

Say I have an NPM package which installs an executable. Presumably I want users to install this package with the -g flag so that they can run it whenever.

In this case, when I call require() from within the executable, it will look for packages installed globally.

But suppose this package provides generic functionality for Node projects. I might want to know which packages the current project has installed locally. Should I just assume:

path.join(process.cwd(), 'node_modules')

Or is there a more "correct" way to set the NODE_PATH in this case? (Or rather than set NODE_PATH, should I just require(absolute_path_to_file)?)

Upvotes: 2

Views: 101

Answers (1)

damphat
damphat

Reputation: 18966

require will not only lookup the package inside $(CWD)\node_modules but also inside all node_modules of parent, grandparent, etc. So you can use resolve on npm to solve this problem

FILE: your_global_command.js

// npm install resolve
var resolve = require('resolve').sync;

// Lookup for local module at current working dir
function require_cwd(name) {
    var absolute_path = resolve(name, { basedir: process.cwd() });
    return require(absolute_path);
}

// Load local express
// this will throw an error when express is not found as local module
var express = require_cwd('express');

I also create a package to require a package at current-working-dir (instead of __dirname of module): https://npmjs.org/package/require-cwd

Upvotes: 1

Related Questions