Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm install (stop process gracefully on preinstall)

How can I make npm install stop (conditionally) within a preinstall script?

Currently I have a preinstall script preinstall.js:

if (someCondition) {
  process.kill(process.ppid, 'SIGKILL');
}

package.json:

{
  "scripts": {
     "preinstall": "node preinstall"
  }
}

However this will result in:

npm ERR! code ELIFECYCLE
npm ERR! errno 1

I would like to exit the process gracefully.

Any ideas?

like image 449
Tim Avatar asked Mar 25 '26 17:03

Tim


1 Answers

The best practice to preventing the installation of a node package it to return a non-zero exit code from the preinstall script.

You'll still get a bunch of npm ERR messages, but it won't kill the npm process like it would with the process.kill option you shared, and would get a proper npm log.

I.e., in preinstall.js, you could have something like this:

if (someCondition) {
    console.error('someCondition happened, aborting installation');
    process.exit(1);
}

And when someCondition is met, you'll see something like this:

$ npm install ~/src/untracked/mypkg/mypkg-1.0.0.tgz

> [email protected] preinstall C:\Users\allon\src\git\samplenode\node_modules\mypkg
> node preinstall

someCondition happened, aborting installation

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] preinstall: `node preinstall`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] preinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/users/mureinik/.npm-cache/_logs/2020-11-29T09_58_46_179Z-debug.log

EDIT:
Capturing the discussion from the comments in the answer body, so it's easier to find if other encounter the same problem. The goal here is to fail the installation of a specific package, without failing the entire npm install process. This behavior can't be controlled by a preinstall script (that can only control whether the package it's part of successfully installs or not), but can be achieved if the dependency is listed in the optionalDependencies section of the package.json.

like image 181
Mureinik Avatar answered Mar 27 '26 07:03

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!