如何修改Node.js默认调试器端口?解决9229端口占用报错
Hey there! Let's break down how to change Node.js's default debugger port and fix that "address already in use" error you're seeing.
There are a few straightforward ways to override the default 9229 port for the Node.js inspector:
Command line direct specification: When starting your app, append the
--inspectflag with your desired port. For example:node --inspect=9230 app.jsIf you need to allow connections from external devices (not just localhost), you can bind to all addresses like this:
node --inspect=0.0.0.0:9230 app.jsNote: For older Node.js versions (pre-v7), use
--debug=9230instead, though theinspectAPI is now the standard.Package.json script configuration: If you use npm scripts to start your app, update the script to include the port flag. For example:
{ "scripts": { "start": "node --inspect=9230 app.js" } }Now running
npm startwill automatically use your custom port.Environment variable: Set the
NODE_INSPECT_PORTenvironment variable before launching Node.js:- On Linux/macOS (bash/zsh):
export NODE_INSPECT_PORT=9230 node app.js - On Windows (Command Prompt):
set NODE_INSPECT_PORT=9230 node app.js - On Windows (PowerShell):
$env:NODE_INSPECT_PORT=9230 node app.js
- On Linux/macOS (bash/zsh):
This error means another process is already using port 9229. Here's how to fix it:
Option 1: Kill the process using port 9229
First, find out which process is hogging the port:
Linux/macOS:
Uselsofto list processes using the port:lsof -i :9229Look for the
PIDcolumn, then kill the process with:kill -9 <PID>If you get a permission error, add
sudobefore the commands.Alternatively, use
netstat:netstat -tulpn | grep 9229Windows:
In Command Prompt, run:netstat -ano | findstr :9229The last number in the output is the PID. Kill the process with:
taskkill /F /PID <PID>Or open Task Manager, go to the "Details" tab, find the process with that PID, and end it.
Option 2: Use a different port instead
If you don't want to kill the existing process, just start your Node app with a custom port as we covered earlier. For example:
node --inspect=9230 app.js
Pro tip: Sometimes the stuck process is a leftover Node.js instance that didn't exit properly. Killing it should resolve the issue for future launches on the default port.
内容的提问来源于stack exchange,提问作者Sasi Rekha

