UNPKG

2.7 kBJavaScriptView Raw
1#!/usr/bin/env node
2const chalk = require('chalk');
3const debug = require('debug')('wait-port');
4const program = require('commander');
5const pkg = require('../package.json');
6const extractTarget = require('../lib/extract-target');
7const ConnectionError = require('../lib/errors/connection-error');
8const TargetError = require('../lib/errors/target-error');
9const ValidationError = require('../lib/errors/validation-error');
10const waitPort = require('../lib/wait-port');
11
12program
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 { protocol, host, port, path } = extractTarget(target);
22 const timeout = program.timeout || 0;
23 const output = program.output;
24 const waitForDns = program.waitForDns;
25
26 debug(`Timeout: ${timeout}`);
27 debug(`Target: ${target} => ${protocol}://${host}:${port}${path}`);
28 debug(`waitForDns: ${waitForDns}`);
29
30 const params = {
31 timeout,
32 protocol,
33 host,
34 port,
35 path,
36 output,
37 waitForDns,
38 };
39
40 const open = await waitPort(params);
41 process.exit(open ? 0 : 1);
42 } catch (err) {
43 // Show validation errors in red.
44 if (err instanceof ValidationError) {
45 console.error(chalk.red(`\n Validation Error: ${err.message}`));
46 process.exit(2);
47 } else if (err instanceof ConnectionError) {
48 console.error(chalk.red(`\n\n Connection Error Error: ${err.message}`));
49 process.exit(4);
50 } else if (err instanceof TargetError) {
51 console.error(chalk.red(`\n Target Error: ${err.message}`));
52 process.exit(4);
53 } else {
54 console.error(chalk.red(`\n Unknown error occurred waiting for ${target}: ${err}`));
55 process.exit(3);
56 }
57 }
58 });
59
60// Enrich the help.
61program.on('--help', () => {
62 console.log(' Examples:');
63 console.log('');
64 console.log(' $ wait-port 3000');
65 console.log(' $ wait-port -t 10 :8080');
66 console.log(' $ wait-port google.com:443');
67 console.log(' $ wait-port http://localhost:5000/healthcheck');
68 console.log(' $ wait-port --wait-for-dns http://mynewdomain.com:80');
69 console.log('');
70});
71
72// Parse the arguments. Spaff an error message if none were provided.
73program.parse(process.argv);
74if (program.args.length === 0) {
75 program.help();
76}