NextNodeTemplate/frontend/scripts/findPort.js
DosAi ea61c5f493
Some checks failed
CI/CD / lint-and-build (push) Has been cancelled
feat: Add automatic free port finder for frontend and backend
2025-11-02 17:39:38 +03:00

57 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Скрипт для поиска свободного порта для Next.js
const net = require('net');
/**
* Проверяет, свободен ли порт
*/
function isPortAvailable(port) {
return new Promise((resolve) => {
const server = net.createServer();
server.listen(port, () => {
server.once('close', () => {
resolve(true);
});
server.close();
});
server.on('error', () => {
resolve(false);
});
});
}
/**
* Находит свободный порт начиная с заданного
*/
async function findFreePort(startPort, maxAttempts = 10) {
for (let i = 0; i < maxAttempts; i++) {
const port = startPort + i;
const available = await isPortAvailable(port);
if (available) {
return port;
}
}
throw new Error(
`Не удалось найти свободный порт в диапазоне ${startPort}-${startPort + maxAttempts - 1}`
);
}
// Если запущен как скрипт
if (require.main === module) {
const startPort = parseInt(process.argv[2]) || 3000;
findFreePort(startPort)
.then((port) => {
console.log(port);
process.exit(0);
})
.catch((error) => {
console.error(error.message);
process.exit(1);
});
}
module.exports = { isPortAvailable, findFreePort };