Skip to content

Commit

Permalink
fix: use available ephemeral ports for app service on production
Browse files Browse the repository at this point in the history
  • Loading branch information
Hrdtr committed Jan 12, 2024
1 parent a4fc7cb commit 015628c
Showing 1 changed file with 43 additions and 5 deletions.
48 changes: 43 additions & 5 deletions lib/electron/main.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,37 @@
import path from 'node:path'
import net from 'node:net'
import { pathToFileURL } from 'node:url'
import { BrowserWindow, app } from 'electron'

process.env.ROOT = path.join(process.resourcesPath)

async function findAvailablePort(startPort, endPort) {
for (let port = startPort; port <= endPort; port++) {
const isPortAvailable = await isPortFree(port)
if (isPortAvailable) return port
}
throw new Error('No available ports in the specified range.')
}
function isPortFree(port) {
return new Promise((resolve) => {
const server = net.createServer()
server.once('error', (err) => {
if (err.code === 'EADDRINUSE') resolve(false)
else throw err
})
server.once('listening', () => {
server.close()
resolve(true)
})
server.listen(port, '127.0.0.1')
})
}

// Ports in the range 49152 to 65535 are often referred to as "private" or "ephemeral" ports -
// and are less likely to be used by other applications.
const startPort = 49152
const endPort = 65535

function createWindow() {
const win = new BrowserWindow({
width: 800,
Expand All @@ -13,15 +41,25 @@ function createWindow() {
},
autoHideMenuBar: true,
})
win.loadURL('http://localhost:3000')
win.loadURL(`http://127.0.0.1:${process.env.PORT || 3000}`)
}

app.whenReady()
.then(async () => {
const modulePath = path.join(process.env.ROOT, '.output/server/index.mjs')
const moduleUrl = pathToFileURL(modulePath).href
const { default: startServer } = await import(moduleUrl)
if (typeof startServer === 'function') startServer()
try {
console.info('finding available port for app service')
const port = await findAvailablePort(startPort, endPort)
process.env.PORT = port
console.info(`starting app service on port ${port}`)

const modulePath = path.join(process.env.ROOT, '.output/server/index.mjs')
const moduleUrl = pathToFileURL(modulePath).href
const { default: startServer } = await import(moduleUrl)
if (typeof startServer === 'function') startServer()
}
catch (error) {
throw new Error('failed to start app service')
}
})
.then(createWindow)

Expand Down

0 comments on commit 015628c

Please sign in to comment.