简体   繁体   中英

Catch exit sign from npm script package.json

is it possible to hook the exit sign of an npm script?

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

I want to be able to call docker-compose down when exiting the script with ctrl+c

With a shell script, this is possible by 'trapping' the signed exit 0

#!/bin/bash

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

docker-compose up &
npm start

done

I would rather not use a shell script so it can be run on other OS than Unix like systems.

I would rather not use a shell script so it can be run on other OS than Unix like systems.

You can write your script in Node.js to make it compatible with any OS where npm start can be run.

#!/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' });

I was able to use your initial script in an npm script (package.json) when running docker compose in the background (-d).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM