1 | #!/usr/bin/env node
|
2 | const chalk = require('chalk');
|
3 | const debug = require('debug')('wait-port');
|
4 | const program = require('commander');
|
5 | const pkg = require('../package.json');
|
6 | const extractTarget = require('../lib/extract-target');
|
7 | const ConnectionError = require('../lib/errors/connection-error');
|
8 | const TargetError = require('../lib/errors/target-error');
|
9 | const ValidationError = require('../lib/errors/validation-error');
|
10 | const waitPort = require('../lib/wait-port');
|
11 |
|
12 | program
|
13 | .version(pkg.version)
|
14 | .description('Wait for a target to accept connections, e.g: wait-port localhost:8080')
|
15 | .option('-t, --timeout [n]', 'Timeout', parseInt)
|
16 | .option('-o, --output [mode]', 'Output mode (silent, dots). Default is silent.')
|
17 | .option('--wait-for-dns', 'Do not fail on ENOTFOUND, meaning you can wait for DNS record creation. Default is false.')
|
18 | .arguments('<target>')
|
19 | .action(async (target) => {
|
20 | try {
|
21 | const options = program.opts();
|
22 | const { protocol, host, port, path } = extractTarget(target);
|
23 | const timeout = options.timeout || 0;
|
24 | const output = options.output;
|
25 | const waitForDns = options.waitForDns;
|
26 |
|
27 | debug(`Timeout: ${timeout}`);
|
28 | debug(`Target: ${target} => ${protocol}://${host}:${port}${path}`);
|
29 | debug(`waitForDns: ${waitForDns}`);
|
30 |
|
31 | const params = {
|
32 | timeout,
|
33 | protocol,
|
34 | host,
|
35 | port,
|
36 | path,
|
37 | output,
|
38 | waitForDns,
|
39 | };
|
40 |
|
41 | const open = await waitPort(params);
|
42 | process.exit(open ? 0 : 1);
|
43 | } catch (err) {
|
44 |
|
45 | if (err instanceof ValidationError) {
|
46 | console.error(chalk.red(`\n Validation Error: ${err.message}`));
|
47 | process.exit(2);
|
48 | } else if (err instanceof ConnectionError) {
|
49 | console.error(chalk.red(`\n\n Connection Error Error: ${err.message}`));
|
50 | process.exit(4);
|
51 | } else if (err instanceof TargetError) {
|
52 | console.error(chalk.red(`\n Target Error: ${err.message}`));
|
53 | process.exit(4);
|
54 | } else {
|
55 | console.error(chalk.red(`\n Unknown error occurred waiting for ${target}: ${err}`));
|
56 | process.exit(3);
|
57 | }
|
58 | }
|
59 | });
|
60 |
|
61 |
|
62 | program.on('--help', () => {
|
63 | console.log(' Examples:');
|
64 | console.log('');
|
65 | console.log(' $ wait-port 3000');
|
66 | console.log(' $ wait-port -t 10 :8080');
|
67 | console.log(' $ wait-port google.com:443');
|
68 | console.log(' $ wait-port http://localhost:5000/healthcheck');
|
69 | console.log(' $ wait-port --wait-for-dns http://mynewdomain.com:80');
|
70 | console.log('');
|
71 | });
|
72 |
|
73 |
|
74 | program.parse(process.argv);
|
75 | if (program.args.length === 0) {
|
76 | program.help();
|
77 | }
|