问题
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?
回答1:
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
> mypkg@1.0.0 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! mypkg@1.0.0 preinstall: `node preinstall`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the mypkg@1.0.0 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
.
回答2:
Did you try to clean cash afterwards delete node_modules then reinstall the dependencies again?
npm cache clean
rm -rf node_modules
npm install
来源:https://stackoverflow.com/questions/65058817/npm-install-stop-process-gracefully-on-preinstall