Skip to content

feat(start): handle EADDRINUSE by asking for another port number #127

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 21, 2020
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 55 additions & 3 deletions src/commands/start.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Argv } from 'yargs';
import inquirer from 'inquirer';
import checkNodejsVersion from '../checks/nodejs-version';
import checkProjectStructure from '../checks/project-structure';
import { getConfigFromCli, StartCliFlags } from '../config/start';
Expand All @@ -9,9 +10,19 @@ import { getDebugFunction, setLogLevelByName } from '../utils/logger';
import { ExternalCliOptions, sharedCliOptions } from './shared';
import { CliInfo } from './types';
import { getFullCommand } from './utils';
import { logger } from '../utils/logger';

const debug = getDebugFunction('twilio-run:start');

type ServerError = Error & {
code: string;
};

function randomPort() {
// Returns a random port number higher than 1024 and lower than 65536.
return Math.floor(Math.random() * (65535 - 1025) + 1025);
}

export async function handler(
argv: StartCliFlags,
externalCliOptions?: ExternalCliOptions
Expand Down Expand Up @@ -41,11 +52,52 @@ export async function handler(

const app = await createServer(config.port, config);
debug('Start server on port %d', config.port);
return new Promise(resolve => {
app.listen(config.port, async () => {
return new Promise((resolve, reject) => {
let attempts = 1;
const MAX_ATTEMPTS = 3;
const serverStartedSuccessfully = async () => {
printRouteInfo(config);
resolve();
});
};
const handleServerError = async (error: ServerError) => {
if (error.code === 'EADDRINUSE') {
if (attempts > MAX_ATTEMPTS) {
logger.info('Too many retries. Please check your available ports.');
process.exit(1);
} else {
const answers = await inquirer.prompt([
{
type: 'input',
default: randomPort(),
name: 'newPortNumber',
message: `Port ${config.port} is already in use. Choose a new port number:`,
validate: input => {
const newPortNumber = parseInt(input, 10);
if (
!Number.isNaN(newPortNumber) &&
newPortNumber <= 65535 &&
newPortNumber > 0
) {
return true;
}
return 'Please enter a port number between 0 and 65535.';
},
},
]);
attempts += 1;
const server = app.listen(
answers.newPortNumber,
serverStartedSuccessfully
);
server.on('error', handleServerError);
}
} else {
reject(error);
}
};

const server = app.listen(config.port, serverStartedSuccessfully);
server.on('error', handleServerError);
});
}

Expand Down