Created
February 26, 2024 06:01
-
-
Save souporserious/36a3dd75c557bcdff31322d757eac3be to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { readFileSync } from 'node:fs' | |
import { resolve } from 'node:path' | |
function extractPort(script: string) { | |
const portRegex = /next dev.*(?:-p |--port )(\d+)/ | |
const match = script.match(portRegex) | |
return match ? match[1] : null | |
} | |
/* Read package.json and parse the Next.js port number */ | |
export function getNextJsDevPort() { | |
const packageJsonPath = resolve(process.cwd(), 'package.json') | |
const packageJson = readFileSync(packageJsonPath, 'utf8') | |
const config = JSON.parse(packageJson) as { | |
scripts?: Record<string, string> | |
} | |
if (config.scripts) { | |
for (const value of Object.values(config.scripts)) { | |
if (value.includes('next dev')) { | |
const port = extractPort(value) | |
if (port) { | |
return parseInt(port) | |
} | |
} | |
} | |
} | |
return 3000 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment