11const runCommand = require ( '../src/utility/run-command' ) ;
22const { execSync } = require ( 'child_process' ) ;
33
4+ function getPidByPort ( port ) {
5+ try {
6+ const stdout = execSync ( `lsof -ti :${ port } ` , { encoding : 'utf8' } ) ;
7+ const pid = stdout . trim ( ) ;
8+ return pid ? parseInt ( pid , 10 ) : null ;
9+ } catch ( error ) {
10+ return null ;
11+ }
12+ }
13+
14+ function killProcByPid ( pid ) {
15+ try {
16+ execSync ( `kill -9 ${ pid } ` , { stdio : 'ignore' } ) ;
17+ } catch ( e ) { }
18+ }
19+
420module . exports = class NextJsServer {
521 constructor ( env , { port } = { port : 3000 } ) {
622 this . proc = null ;
@@ -9,8 +25,15 @@ module.exports = class NextJsServer {
925 }
1026
1127 async start ( ) {
12- await this . stop ( ) ;
28+ if ( process . platform !== 'win32' ) {
29+ let pid ;
30+ while ( pid = getPidByPort ( this . port ) ) {
31+ console . log ( `-----NEXTJS SERVER-start() kill for port ${ this . port } ---->` ) ;
32+ killProcByPid ( pid ) ;
33+ }
34+ }
1335
36+ await new Promise ( ( resolve ) => setTimeout ( resolve , 1000 ) ) ;
1437 console . log ( '----RUN START SERVER CMD------>' ) ;
1538 ( { proc : this . proc } = await runCommand ( 'npx' , [ 'next' , 'start' , `-p ${ this . port } ` ] , {
1639 cwd : this . env . appPath ,
@@ -27,15 +50,16 @@ module.exports = class NextJsServer {
2750 await new Promise ( ( resolve ) => setTimeout ( resolve , 1000 ) ) ;
2851 }
2952
30- if ( process . platform !== 'win32' ) {
31- console . log ( `-----NEXTJS SERVER-exec kill for port ${ this . port } ---->` ) ;
32- try {
33- execSync ( `lsof -i :${ this . port } -t | xargs kill -9` , { stdio : 'ignore' } ) ;
34- await new Promise ( ( resolve ) => setTimeout ( resolve , 1000 ) ) ;
35- } catch ( e ) {
36- console . log ( `NextJs server on port ${ this . port } not found. It's OK` ) ;
37- this . proc = null ;
38- }
53+ if ( process . platform === 'win32' ) {
54+ return ;
55+ }
56+
57+ console . log ( `-----NEXTJS SERVER-exec kill for port ${ this . port } ---->` ) ;
58+ try {
59+ execSync ( `lsof -i :${ this . port } -t | xargs kill -9` , { stdio : 'ignore' } ) ;
60+ } catch ( e ) {
61+ console . log ( `NextJs server on port ${ this . port } not found. It's OK` ) ;
62+ this . proc = null ;
3963 }
4064 }
4165} ;
0 commit comments