[英]Can anyone help me with the math for an express port randomizer
我的機器人一直在破壞數據並隨機崩潰並發現了問題,就是這段代碼:
Math.floor(Math.random()*6000)
誰能幫我這個? 另外,這是我的整個 express.js 文件:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('DSB is online')
})
app.listen(port, () => {
console.log(`BOT listening at http://localhost:${port}`)
})
它說 3000 因為那是原始的。 我已經改變了它,這幾乎就是它所說的。
您可以將隨機數更改為最小值。 正如CertainPerformance 在他們的評論中提到的那樣,從1000(或者可能是1024)而不是零開始是個好主意。 您當前的代碼將返回一個介於 0 和 6000 之間的數字(包括 0 但不包括 6000)。
下面的 function 將生成一個介於min
和max
之間的隨機 integer。
function randomInt(min = 1024, max = 6000) {
if (min > max) {
[min, max] = [max, min]
}
return Math.floor((Math.random() * ((max - min) + 1)) + min)
}
randomInt() // => 5302
你可以像這樣使用它:
app.get('/', (req, res) => {
res.send('DSB is online')
})
const server = app.listen(randomInt(), () => {
console.log(`BOT listening on port ${server.address().port}`)
// => BOT listening on port 5981
})
在 Express 中,如果你想隨機分配一個端口,你可以簡單地監聽端口0
:
app.get('/', (req, res) => {
res.send('DSB is online')
})
const server = app.listen(0, () => {
console.log(`BOT listening on port ${server.address().port}`)
// => BOT listening on port 58319
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.