Capture the exit signal from the npm script defined in the package.json file

Is it feasible to intercept the exit signal of an npm script?

"scripts": {
    "serve": "docker-compose up && npm start"
}

I am interested in implementing docker-compose down when terminating the script using ctrl+c

In a shell script, this can be achieved by 'trapping' the signal for exiting with 0

#!/bin/bash

trap 'docker-compose down ; echo Stopped ; exit 0' SIGINT

docker-compose up &
npm start

done

I prefer to avoid using a shell script so that the script can run on non-Unix operating systems as well.

Answer №1

When setting up my project, I incorporated your initial script into an npm script within the package.json file to run docker compose in the background (-d).

"scripts": {
   ...
   "up": "trap 'docker-compose down ; echo Stopped ; exit 0' SIGINT; docker-compose up -d && npm start"
   ...
}

Answer №2

I prefer not to rely on a shell script in order for it to be executable on various operating systems beyond just Unix-like systems.

To ensure compatibility across different OS platforms, consider writing your script in Node.js so that it can be executed wherever npm start is supported.

#!/usr/bin/env node

'use strict';
const childProcess = require('child_process');

childProcess.spawnSync('docker-compose', ['up'], { stdio: 'inherit'});

process.on('SIGINT', () => {
  console.log('SIGINT caught, running docker-compose down');
  childProcess.spawnSync('docker-compose', ['down'], { stdio: 'inherit' });
  process.exit(0);
});

console.log('go ahead, press control-c');
childProcess.spawnSync('npm', ['start'], { stdio: 'inherit' });

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

Is there a way to verify if a word contains parentheses using regular expressions?

Is there a way to use regular expressions in JavaScript to identify words that are surrounded by square brackets, like this: "I love [coding] and [creating]"? I attempted the following code, but it didn't yield the desired results. if(data.word.matc ...

Toggle Visibility of Div Based on Matching Class Name When Clicked

Just delving into the world of jQuery and could use some guidance. Is there a way to show a div with a matching class when a specific button is clicked? For example, clicking on a button with the class '.project1' should display the corresponding ...

Change the CSS menu item to directly load the website instead of using javascript to replace a placeholder

I have a CSS navigation menu, but I'm facing an issue. When I click on a link in the menu, like Google for example, it only changes the name of the placeholder and doesn't actually load the page. Any suggestions on how to fix this? Thank you for ...

Angular2's hidden feature isn't functioning properly

There is a common suggestion to use *ngIf better than [hidden] but in my scenario, I want to keep the element in the DOM without it being visible. In my component.html file, I have: <article #articleId id="bodyArticle" [hidden]="isClicked"></art ...

How can I retrieve the value from the input field using vue.js?

I am currently utilizing the vue-js-toggle-button library. While I understand that I can access the value inside the name using $refs, the issue arises as I have 3 toggle buttons and cannot set a Ref because I want to retrieve the name value dynamically i ...

Getting URL parameters in NextJS when using Custom Document can be achieved by accessing the `ctx`

Currently, I am utilizing NextJS for generating SSR pages that are language-specific. I want to specify the lang property to indicate the language of the text. Here's what I have done so far: import Document, { Html, Head, Main, NextScript } from &qu ...

Video playback disabled on hover in Chrome browser

I have added videos to a search results page. When the user hovers over the video, I want to show a preview of it in a separate container and start playing the video. $(".videoSearchResults video").mouseenter(function () { var container = document.cre ...

What is the best way to implement the settimeout method in react?

I need assistance on how to effectively utilize the setTimeout() method in my code. Specifically, I am looking to trigger a click event on an element after a certain delay and execute a function afterwards. Here is the current implementation of my code: ...

Determine the number of radio buttons selected in each group (At least 2 selections in total)

I am looking to validate 7 sets of Radio Buttons, ensuring that a minimum of 2 sets are selected. If not, an alert should be displayed. However, it's important to note that there are additional radio buttons on the page that are not part of this valid ...

Conceal a request URL within JavaScript through the use of Laravel/Ajax

I have an idea that I'm not sure is great or even feasible, but I really need to make it work. I am attempting to obfuscate a URL that needs to be used in a Javascript function as a parameter. This is what I currently have: <script> myFunction ...

angularjs Populate input fields with default values within ng-repeat loop

Our challenge is to display input text with pre-filled values within a list using the ng-repeat directive. <ul ng-repeat="post in postList> <input type="text" ng-model="postid" nginit="postid='{{post.id}}'"></input> </u ...

Having difficulty executing the command 'npm install -g expo-cli'

When attempting to execute npm install - g expo-cli on a Windows 10 machine, I am encountering issues. An error message keeps popping up and preventing me from proceeding. I'm in desperate need of assistance! npm WARN deprecated <a href="/cdn-cgi/ ...

How to create a Vue.js animated navbar with scroll opacity

I am looking to create a fixed navbar that changes opacity based on user scrolling behavior. Initially, I want the navbar background to be transparent and then transition to white as the user scrolls down the page. An example of what I am trying to achieve ...

The personalized confirmation dialog is experiencing malfunctions

I have designed my own custom dialogs using Bootstrap and jQuery, such as Alert and ConfirmDialog. Here is a sample: http://jsfiddle.net/eb71eaya/ The issue I am facing is that in the callback function, I make an AJAX call. If it returns true, I want to ...

Submit a collection of images and an object to the server using ReactJS

I'm currently working with Reactjs on the frontend. In order to set the profile picture to state, I've implemented the following code: handleImageChange = (event) => { event.preventDefault(); var file = event.target.files[ ...

Uploading Files with Ajax - Script Corrupts Files during Upload

My Ajax-Fileupload Script is causing some issues for me. Whenever I upload files, they seem to become corrupt. Opening the file in Notepad++, I can see strange lines such as: -----------------------------22998260013704 Content-Disposition: form-data; name ...

What is the best way to determine the midpoint index of an array?

As a newcomer, I have a question regarding a recent assignment. The task involves creating a global array where objects are imported as they are entered into an input field on the HTML document. The challenge is to update the current list on the document ...

I am seeking guidance on creating a dynamic search feature using node.js and mongoDb. Any input regarding

I am currently working on implementing a unique feature that involves having an input field on this specific page. This input allows users to perform a live search of employees stored in the database. app.get('/delete' , isLoggedIn , (req , res) ...

Using SetTimeOut in THREE JS

I'm currently working on a project for my master's degree that involves creating a space invaders game using three.js. While the project is progressing well, I've encountered a problem with my aliens (THREE.Mesh object) being able to fire r ...

What is the process for enabling external host access to a port in a Docker container?

I've been working on exposing a port in my Docker container and attempting to connect an application from an external host, but I'm having trouble establishing a connection. Here is the curl request: curl http://localhost:4400 curl: (56) Recv fa ...