0

We are developing an npm package, a library, that is going to be included in other projects. This package sometimes has to run a shell script: it calls Prettier using ${somePath}/node_modules/prettier/bin/prettier.js with some parameters.

The problem is that, because of the way node_modules is generated, the location of that prettier.js script doesn't seem to be guaranteed. It may be directly under the node_module folder of the package, for example :

mainProject/node_modules/ourNpmPackage/node_modules/prettier/bin/prettier.js

or it can be moved by npm to the root node_module folder :

mainProject/node_modules/prettier/bin/prettier.js

Our script has to know the location of this .js to call it! What is the recommended way of locating it?

Would it be possible to first check in the local node_modules, then, if prettier is not found, in the parent's node_modules, etc until the package is found? Would this be a solid solution?

electrotype
  • 8,342
  • 11
  • 59
  • 96
  • You should not take any assumptions about the structure of the `node_modules` hierarchy. If possible you should use something like `require('prettier/bin/prettier.js')` which should resolve to the file you are looking for. – t.niese Jan 09 '18 at 17:56
  • @t.niese We launch our script using a variation of `execFile(...)`. How can this `require` help us finding the location of the target file? Thanks. – electrotype Jan 09 '18 at 18:01
  • Oh! Thanks for the link, it seems `require.resolve('module');` is the solution! – electrotype Jan 09 '18 at 18:03
  • 1
    Some modules export a function in the bin script that allows to call them with the command line arguments. Otherwise you can use the linked duplicate to get the path. – t.niese Jan 09 '18 at 18:05
  • Using `execFile` on a `bin/*.js` is in most cases just a work around. Normally all module should provide a simple ways to use is as if it was called form command line. And you should always prefere an API solution over the the `exeFile` solution. – t.niese Jan 09 '18 at 18:11

0 Answers0