|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +let spawn = require('child_process').spawn; |
| 4 | + |
| 5 | +// |
| 6 | +//USE: ./index.js <ms npm can be idle> <number of attempts> [... NPM ARGS] |
| 7 | +// |
| 8 | + |
| 9 | +let timeout = process.argv[2] || 60000; |
| 10 | +let attempts = process.argv[3] || 3; |
| 11 | +let args = process.argv.slice(4); |
| 12 | +if (args.length === 0) { |
| 13 | + args = ['install']; |
| 14 | +} |
| 15 | + |
| 16 | +(function npm() { |
| 17 | + let timer; |
| 18 | + args.push('--verbose'); |
| 19 | + let proc = spawn('npm', args); |
| 20 | + proc.stdout.pipe(process.stdout); |
| 21 | + proc.stderr.pipe(process.stderr); |
| 22 | + proc.stdin.end(); |
| 23 | + proc.stdout.on('data', () => { |
| 24 | + setTimer(); |
| 25 | + }); |
| 26 | + proc.stderr.on('data', () => { |
| 27 | + setTimer(); |
| 28 | + }); |
| 29 | + |
| 30 | + // side effect: this also restarts when npm exits with a bad code even if it |
| 31 | + // didnt timeout |
| 32 | + proc.on('close', (code, signal) => { |
| 33 | + clearTimeout(timer); |
| 34 | + if (code || signal) { |
| 35 | + console.log('[npm-are-you-sleeping] npm exited with code ' + code + ''); |
| 36 | + |
| 37 | + if (--attempts) { |
| 38 | + console.log('[npm-are-you-sleeping] restarting'); |
| 39 | + npm(); |
| 40 | + } else { |
| 41 | + console.log('[npm-are-you-sleeping] i tried lots of times. giving up.'); |
| 42 | + throw new Error("npm install fails"); |
| 43 | + } |
| 44 | + } |
| 45 | + }); |
| 46 | + |
| 47 | + function setTimer() { |
| 48 | + clearTimeout(timer); |
| 49 | + timer = setTimeout(() => { |
| 50 | + console.log('[npm-are-you-sleeping] killing npm with SIGTERM'); |
| 51 | + proc.kill('SIGTERM'); |
| 52 | + // wait a couple seconds |
| 53 | + timer = setTimeout(() => { |
| 54 | + // its it's still not closed sigkill |
| 55 | + console.log('[npm-are-you-sleeping] killing npm with SIGKILL'); |
| 56 | + proc.kill('SIGKILL'); |
| 57 | + }, 2000); |
| 58 | + }, timeout); |
| 59 | + } |
| 60 | +})(); |
0 commit comments