import { execFileSync , execSync , ExecSyncOptionsWithStringEncoding } from 'child_process' ; import * as path from 'path' ; const defaultOptions = { encoding : 'utf8' , stdio : [ 'pipe' , 'pipe' , 'ignore' ] } ; function getPID ( port ) { return execFileSync ( 'lsof' , [ `-i:${ port }` , '-P' , '-t' , '-sTCP:LISTEN' ] , defaultOptions ) . split ( '\n' ) [ 0 ] . trim ( ) ; } function getPackageName ( packageRoot ) { const packageJson = path . join ( packageRoot . trim ( ) , 'package.json' ) ; try { return require ( packageJson ) . name || null ; } catch { return null ; } } function getProcessCommand ( pid , procDirectory ) { const results = execSync ( `ps -o command -p ${ pid } | sed -n 2p` , defaultOptions ) . replace ( /\n$/ , '' ) . trim ( ) ; const name = getPackageName ( procDirectory ) ; return name ? name : results ; } function getDirectoryOfProcessById ( processId ) { return execSync ( 'lsof -p ' + processId + ' | awk \'$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}\'' , defaultOptions ) . trim ( ) ; } export function getRunningProcess ( port ) { try { const pid = getPID ( port ) ; const directory = getDirectoryOfProcessById ( pid ) ; const command = getProcessCommand ( pid , directory ) ; return { pid , directory , command } ; } catch { return null ; } }