npm / npx

npm package executor

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[QUESTION] How do I get access to the directory of the module containing it, if any?

mercmobily opened this issue · comments

What / Why

I have an entry in my package.json:

  "bin": {
    "js-kit": "./bin/kit.js"
  },

Say I am in ~package/some/subdir and run:

npx js-kit

The executable will be called. However, kit.js (the actual program) only has access to CWD (being ~package/some/subdir) rather than ~package (which is what I am interested in).

Is there any way to know on behalf of what package the script was run?
I DO realise that if the script is run directly (node_modules/.bin/js-kit) or if js-kit is installed globally, there won't be a "module directory". But IF it's run from a local module (not globally), via npx, do I have access to the hosting module's full path?

Why would you run a command anywhere but in the root of a package?

You should have access; your package can use https://www.npmjs.com/package/find-package-json for example.

Alright, answering myself and closing the issue:

  • No, npx doesn't use find-package-json, but a home baked solution
  • No, npx doesn't export the name of the package it belongs to
  • No, the use case of packages needing to know the name of the "hosted" package is way too small, and won't be exported

Too easy -- thanks!