Generate a stable and unique port number for the project (range 3000-8999); the same project name always returns the same port.
Port generation algorithm
def generate_port(project_name: str) -> int:
hash_value = sum(ord(c) * (i + 1) for i, c in enumerate(project_name))
return 3000 + (hash_value % 6000)
Use cases
1. Query the project port
When the user asks about the port, calculate it directly and inform them:
项目 "lovstudio" 的端口号是:7965
2. Update the project configuration
Detect and update the port configuration file in the project:
| File | Configuration method |
|---|---|
.env / .env.local |
PORT=<port> |
package.json |
In scripts --port <port> |
vite.config.ts |
server.port: <port> |
next.config.js |
Usually use .env |
When updating, prefer the .env method, for minimal intrusiveness.
3. Start the development server
PORT=$(scripts/hashport.sh) pnpm dev
Script
Run scripts/hashport.sh [project-name] to generate the port:
# 使用当前目录名
./scripts/hashport.sh
# 输出: 7965
# 指定项目名
./scripts/hashport.sh my-project
# 输出: 5123
Port conflict handling
If the port is occupied:
- Tell the user which process is occupying the port
- Suggest using
lsof -i :<port>to check - A suffix can be appended to generate an alternative port:
generate_port("project-dev")