简体   繁体   English

从 npm 脚本 package.json 中捕获退出标志

[英]Catch exit sign from npm script package.json

is it possible to hook the exit sign of an npm script?是否可以挂钩 npm 脚本的退出标志?

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

I want to be able to call docker-compose down when exiting the script with ctrl+c我希望能够在使用ctrl+c退出脚本时调用docker-compose down

With a shell script, this is possible by 'trapping' the signed exit 0使用 shell 脚本,这可以通过“捕获”签名出口 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.我宁愿不使用 shell 脚本,这样它就可以在 Unix 类系统以外的其他操作系统上运行。

I would rather not use a shell script so it can be run on other OS than Unix like systems.我宁愿不使用 shell 脚本,这样它就可以在 Unix 类系统以外的其他操作系统上运行。

You can write your script in Node.js to make it compatible with any OS where npm start can be run.您可以在 Node.js 中编写脚本,使其与任何可以运行npm start操作系统兼容。

#!/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).在后台运行 docker compose (-d) 时,我能够在 npm 脚本 (package.json) 中使用您的初始脚本。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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