LimeStreem LimeStreem - 5 months ago 16
Node.js Question

Is there good way to run a script only when the user install my npm package manually?(not installed by dependency)

I'm under developing my npm package and I want to run a specific script only when user installed my package manually like

npm install my-package --save-dev
or something npm command.

I'd not like to run the command when the package was installed via package dependency.
For example, My package is dependency of the other package
Even if the user installed
manually and npm should install
as dependency, I'd not like to run the script.

Is there good way to handle this?


npm has a set of scripts that will automatically run when npm is launched a particular way. The scripts you might be interested in are:

  • prepublish: Run BEFORE the package is published. (Also run on local npm install without any arguments.)
  • publish, postpublish: Run AFTER the package is published.
  • preinstall: Run BEFORE the package is installed
  • install, postinstall: Run AFTER the package is installed.

There is no event that exactly matches your criteria but you could use one of the install events and then have an intermediate script that detects the npm command line options before your actual script.

Due to the (imo horrible) way prepublish works, a number of people have written modules to do a similar task and these could easily be adapted to your requirements.

iarna/inpublish is a good example. It check's process.env['npm_config_argv'] for the existence of /^i(n(s(t(a(ll?)?)?)?)?)?$/

Using the following package.json setup:

"scripts": {
  "postinstall": "my-install && install-manual-tasks || not-my-install"

If my-install uses process.exit(0) then install-manual-tasks will run. If you process.exit(1), not-my-install will clean up so the npm task doesn't fail.

I think this setup actually has an issue. If your install-manual-tasks fails, the exit status is silenced and the npm task won't fail but it's a start at least. You could work around this by doing all your checks in the install-manual-tasks script, then you don't need use the shell tricks to run multiple scripts.