Get the ID of the process that uses a certain port
Install
npm install pid-port
Usage
import {portToPid} from 'pid-port';try { // Only checks localhost by default console.log(await portToPid(8080)); //=> 1337 // Same as above console.log(await portToPid({port: 8080})); //=> 1337 const pids = await portToPid([8080, 22]); console.log(pids.get(8080)); //=> 1337 console.log(pids.get(22)); //=> 12345
API
portToPid(portOrOptions)
Get the process ID for a port.
Returns a Promise<number | undefined>(integer) with the process ID.
[!NOTE]
By default, only checks localhost (127.0.0.1 and ::1). Use {host: '*'} to check all interfaces if needed.
Linux privilege requirements: On Linux systems, process ID information may not be visible to non-privileged users. If a port is found but no PID is returned, the package will attempt to use lsof as a fallback (requires lsof to be installed).
portOrOptions
Type: number | {port: number, host?: string}
Either a port number directly, or an options object with:
port(number): The port to look up
host(string, optional): The host to filter by. Use '*', '0.0.0.0', or '::' for all interfaces. Use 'localhost' for explicit localhost filtering.
portToPid(ports)
Get the process IDs for multiple ports.
Returns a Promise<Map<number, number>>(integer) with the port as key and the process ID as value.
import {portToPid} from 'pid-port';try { const pids = await portToPid([8080, 22]); console.log(pids.get(8080)); //=> 1337 console.log(pids.get(22)); //=> 12345} catch (error) { console.log(error); //=> 'Could not find a process that uses port `8080`'}
ports
Type: number[](integer)
The ports to look up.
pidToPorts(pid)
Get the ports for a process ID.
Returns a Promise<Set<number>> with the ports.
import {pidToPorts} from 'pid-port';try { const ports = await pidToPorts(1337); //=> Set { 8080, 22 }} catch (error) { console.log(error);}
pid
Type: number
The process ID to look up.
pidToPorts(pids)
Get the ports for multiple process IDs.
Returns a Promise<Map<number, Set<number>>> with the process ID as the key and the ports as value.