My bot has been corrupting data and randomly crashing and found the problem, it was this bit of code:
Math.floor(Math.random()*6000)
Can anyone help me with this? Also, here is my entire express.js file:
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}`)
})
It says 3000 because that's the original one. I've changed it and that's almost what it says.
You can change the random number to have a minimum value. As CertainPerformance mentioned in their comment it's a good idea to start at 1000 (or maybe 1024) and not zero. Your current code will return with a number between 0 and 6000 (inclusive of 0 but not 6000).
The following function will generate a random integer between a min
and max
value.
function randomInt(min = 1024, max = 6000) {
if (min > max) {
[min, max] = [max, min]
}
return Math.floor((Math.random() * ((max - min) + 1)) + min)
}
randomInt() // => 5302
And you can use it like this:
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
})
In Express, if you want to randomly assign a port, you can simply listen on port 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
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.