@@ -30,6 +30,11 @@ const tryParseInt = require('../lib/utils/tryParseInt');
30
30
31
31
let server ;
32
32
33
+ // Taken out of yargs because we must know if
34
+ // it wasn't given by the user, in which case
35
+ // we should use portfinder.
36
+ const DEFAULT_PORT = 8080 ;
37
+
33
38
const signals = [ 'SIGINT' , 'SIGTERM' ] ;
34
39
35
40
signals . forEach ( ( signal ) => {
@@ -103,20 +108,6 @@ const config = require(convertArgvPath)(yargs, argv, {
103
108
outputFilename : '/bundle.js' ,
104
109
} ) ;
105
110
106
- // Taken out of yargs because we must know if
107
- // it wasn't given by the user, in which case
108
- // we should use portfinder.
109
- const DEFAULT_PORT = 8080 ;
110
-
111
- // Try to find unused port and listen on it for 3 times,
112
- // if port is not specified in options.
113
- // Because NaN == null is false, defaultTo fails if parseInt returns NaN
114
- // so the tryParseInt function is introduced to handle NaN
115
- const defaultPortRetry = defaultTo (
116
- tryParseInt ( process . env . DEFAULT_PORT_RETRY ) ,
117
- 3
118
- ) ;
119
-
120
111
function processOptions ( config ) {
121
112
// processOptions {Promise}
122
113
if ( typeof config . then === 'function' ) {
@@ -205,26 +196,45 @@ function startDevServer(config, options) {
205
196
}
206
197
} ) ;
207
198
} ) ;
208
- } else if ( options . port ) {
209
- runServer ( ) ;
210
199
} else {
211
- // only run port finder if no port as been specified
212
- findPort ( server , DEFAULT_PORT , defaultPortRetry , ( err , port ) => {
213
- if ( err ) {
200
+ decidePort ( server , options . port )
201
+ . then ( ( port ) => {
202
+ options . port = port ;
203
+ server . listen ( options . port , options . host , ( err ) => {
204
+ if ( err ) {
205
+ throw err ;
206
+ }
207
+ } ) ;
208
+ } )
209
+ . catch ( ( err ) => {
214
210
throw err ;
215
- }
216
- options . port = port ;
217
- runServer ( ) ;
218
- } ) ;
211
+ } ) ;
219
212
}
213
+ }
220
214
221
- function runServer ( ) {
222
- server . listen ( options . port , options . host , ( err ) => {
223
- if ( err ) {
224
- throw err ;
225
- }
226
- } ) ;
227
- }
215
+ function decidePort ( server , port ) {
216
+ return new Promise ( ( resolve , reject ) => {
217
+ if ( typeof port !== 'undefined' ) {
218
+ resolve ( port ) ;
219
+ } else {
220
+ // Try to find unused port and listen on it for 3 times,
221
+ // if port is not specified in options.
222
+ // Because NaN == null is false, defaultTo fails if parseInt returns NaN
223
+ // so the tryParseInt function is introduced to handle NaN
224
+ const defaultPortRetry = defaultTo (
225
+ tryParseInt ( process . env . DEFAULT_PORT_RETRY ) ,
226
+ 3
227
+ ) ;
228
+
229
+ // only run port finder if no port as been specified
230
+ findPort ( server , DEFAULT_PORT , defaultPortRetry , ( err , port ) => {
231
+ if ( err ) {
232
+ reject ( err ) ;
233
+ }
234
+ resolve ( port ) ;
235
+ } ) ;
236
+ }
237
+ } ) ;
228
238
}
229
239
230
240
processOptions ( config ) ;
0 commit comments