简体   繁体   中英

How do I locate a binary installed by one of my NPM package's dependencies so I can execute it?

I have an NPM package which depends on node-pg-migrate . From inside my package, I need to execute node-pg-migrate 's binary pg-migrate . I'm running node 0.12.13.

If the app I've installed my package in doesn't also depend on node-pg-migrate , this is trivial. The dependency is installed in a node_modules directory inside my package.

- node_modules
| - my-package
  | - node_modules
    | - node-pg-migrate

Here's what I would do in that case

exec('./node_modules/node-pg-migrate/bin/pg-migrate up', 
  function(error, stdout, stderr) { 
    // do something
  }
);

However, if the app I'm installing my package to also depends on node-pg-migrate , it will instead be installed in the app's node_modules directory alongside my package.

- node_modules
| - my-package
| - node-pg-migrate

I've thought about first checking my package's node_modules for pg-migrate and backing out one level if it isn't there, but that breaks down if my package is an inner dependency. Then, I might have to try going out one more level.

- node_modules
| - node-pg-migrate?
| - some-package
  | - node_modules
    | - node-pg-migrate?
    | - my-package
      | - node_modules
        | - node-pg-migrate?

How can I find the location of the pg-migrate binary and run it no matter where it falls in the dependency tree?

Since you're executing the pg-migrate binary from the command line, it's recommended that you install it globally

From the npm-folders documentation :

  • Local install (default): puts stuff in ./node_modules of the current package root.
  • Global install (with -g): puts stuff in /usr/local or wherever node is installed.
  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line.
  • If you need both, then install it in both places, or use npm link.

With a global installation you would not need to bother where the package was installed and would be able to execute the migrate command in this manner:

exec('pg-migrate up', 
  ...
);

npm installs links to the various executables within node_modules in the .bin directory, so you don't need to go look for them in specific sub-directory.

So to get to the path you need, you can simply do this:

const myExePath = __dirname + '/node_modules/.bin/my-exe';
const binDir = execFileSync('npm', ['bin']).toString().trim();

exec(binDir + ' pg-migrate up', 
  function(error, stdout, stderr) { 
    // do something
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM