Before installing npm packages, ensure to gracefully stop the process during pre-installation

Is there a way to stop the npm install process conditionally within a preinstall script?

At the moment, I have a preinstall script named preinstall.js:

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

The content of my package.json file is as follows:

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

But this setup leads to the following error message:

npm ERR! code ELIFECYCLE
npm ERR! errno 1

I would prefer to terminate the process in a more graceful manner. Any suggestions on how to achieve this?

Answer №1

To prevent the installation of a node package, it is recommended to ensure that the preinstall script returns a non-zero exit code.

Although you may still see npm ERR messages, the npm process will not be terminated as it would be with the process.kill method mentioned earlier, resulting in a proper npm log.

For instance, in the preinstall.js file, you could include something like this:

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

If someCondition is met, it will display a message similar to 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 occurred, halting 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:
I am summarizing the conversation from the comments within the answer for easier reference if others encounter the same issue. The objective here is to prevent the installation of a specific package without halting the entire npm install process. While this behavior cannot be controlled by a preinstall script (which only affects the current package's installation success), it can be achieved by listing the dependency in the optionalDependencies section of the package.json.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I have a query regarding the load function and JSON

Is it feasible to achieve something similar to this? $.ajax({ url: "test.php", success: function(json, json1){ //I wonder if I can have more than one parameter here? $m0 = []; $m0.push(parseFloat(json)); alert($m0); //display 750 $m1 ...

html5-jquery checkbox change event not firing

I successfully implemented an on/off switch using the method outlined in for HTML5. The functionality of the switch itself is working perfectly - click on it to toggle between states and query the checked state of the input/checkbox. However, I am facing ...

Is the behavior of String.replace with / and different in Node.js compared to Chrome?

Creating a router in Node.js involves mapping URIs to actions, which requires an easily configurable list of URIs and regular expressions to match against the request URI. This process may seem familiar if you have experience with PHP. To test this functi ...

Issue with Material UI Textfield functionality on mobile Safari browser

UPDATE: Resolved the problem by including this code in index.css input { -webkit-user-select:text;} In my application, I am using a Material UI box that contains text fields with an onChange handler. While the TextFields function correctly on most bro ...

Utilizing JavaScript in AJAX Responses

Can I include JavaScript in an AJAX response and run it, or should I only use JSON or plain HTML for a more elegant solution? I'm trying to figure out the best way to handle AJAX requests that involve inserting HTML or running JavaScript based on user ...

Problems with Navbar rendering on multiple occasions

GENERAL INFO I've encountered an issue with the re-rendering of my sidemenu in Gatsby. Despite my efforts, I can't prevent the sidemenu from re-rendering and overriding the data that I set for it. const [activeParent, setActiveParent] = useState ...

At times, JavaScript interacts with Selenium to click on the login button before I have the chance

I have a challenge while attempting to log in to Twitter using Selenium webdriver, here is the code I am working with: const {Builder, By} = require("selenium-webdriver"); (async function example() { let driver = await new Builder().forBrowser(' ...

Issue encountered during installation: npm is unable to install protractor or selenium-webdriver due to a gyp ERR! build error

While working on an Angular project, I encountered an issue with installing Protractor and Selenium WebDriver for testing the E2E tests that I wrote. The error message that appeared was: gyp ERR! build error gyp ERR! stack Error: `make` failed with exit ...

The key to successful filtering in Next.js with Hasura is timing - it's always a step

I am fetching data from Hasura using useRecipe_Filter and passing the searchFilter state as a variable. It seems that every time I press a key, the UI updates with one keystroke delay before filtered data is passed to the results state. const SearchBar = ( ...

Learn how to render list items individually in Vue.js using the 'track-by $index' directive

Recently, I switched from using v-show to display elements in an array one at a time in my Vue instance. In my HTML, I had this line: <li v-for="tweet in tweets" v-show="showing == $index">{{{ tweet }}}</li>". The root Vue instance was set up l ...

Make sure to include !important for the hidden property when applying inline styles in React jsx

Is there a way to include !important in the hidden property within React JSX inline style? I'm attempting to conceal the scroll bar in an Ag Grid table component as it is displayed by default. I've already attempted: ref={(nod ...

Tips on utilizing recursive Promises within a loop while transferring arguments to another function

Despite searching other threads on SO, I couldn't find a satisfactory answer to my problem. Every solution seems to be missing something essential for my case, especially since none of them address Apple Music specifically. The Apple API relies heavil ...

Icon for local system displayed on browser tab

I am currently trying to set a Browser Tab icon for the local system, but it is not working. However, when using an HTTP static icon, it works perfectly. Can someone please help me understand what the issue might be? PAGE 1 : Icon Not Showing <link re ...

What is the best way to implement Axios for data fetching in Gatsby's useStaticQuery function?

One way to fetch data in Gatsby is by using GraphQL, like in the following example: import { graphql, useStaticQuery } from "gatsby" const IndexPage = () => { const gatsbyRepoData = useStaticQuery(graphql` { github { repo ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

Error encountered in Liferay's npm-react-portlet: the module has not been defined

Currently, I am in the process of developing a React portlet for Liferay 7.0 CE. To kickstart this project, I utilized the blade command (directly from the Liferay react template). blade create -t npm-react-portlet -p fi.liferay.react.portlet -c ReactMain ...

Sending Data from Browser to Node.js using Ajax

I've been struggling to send an AJAX post request to my Node server built with Express for a while now. Despite reading various solutions on similar issues, I couldn't figure out which files to edit. Initially, I attempted using `http.createServe ...

switching the content of an element using Javascript

I'd like to switch between two icons when clicking on .switch and apply the style of .nightTextNight to .nightText, my JavaScript code is working well everywhere except here. Is there a simpler way to achieve this? I currently have to create two clas ...

Leveraging jest.unmock for testing the functionality of a Promise

I've implemented Auth0 for managing authentication in my React App. Below is the code snippet I am trying to test: login(username: string, password: string) { return new Promise((resolve, reject) => { this.auth0.client.login({ ...

Tips for capturing text input from a Quill rich text editor div

My attempt to retrieve the content entered in Quill editor's editor div using jQuery codes is not proving successful. Although it works for other text inputs, it fails to do so for the editor div. Below is a demonstration of the issue: $(function() ...