【发布时间】:2020-03-08 04:42:12
【问题描述】:
我想从文件中获取随机行到我的不和谐机器人,但我不知道如何。
aleadry 尝试了网站上的一些东西,但根本没有帮助,它们都不起作用。
有什么帮助吗?
[js]
【问题讨论】:
-
向我们展示您的尝试
标签: javascript node.js discord node-modules discord.js
我想从文件中获取随机行到我的不和谐机器人,但我不知道如何。
aleadry 尝试了网站上的一些东西,但根本没有帮助,它们都不起作用。
有什么帮助吗?
[js]
【问题讨论】:
标签: javascript node.js discord node-modules discord.js
你可以使用这个方法:
function getRandomLine(filename){
fs.readFile(filename, function(err, data){
if(err) throw err;
var lines = data.split('\n');
// this is random line
const readedLine = lines[Math.floor(Math.random()*lines.length)];
console.log(readedLine);
})
}
有关更多信息,您可以阅读以下内容: Grabbing a random line from file
【讨论】:
虽然其他解决方案有效,但您可以使用此代码同步执行,使其更易于使用:
function getRandomLine(filename){
var data = fs.readFileSync(filename, "utf8");
var lines = data.split('\n');
return lines[Math.floor(Math.random()*lines.length)];
}
var the_random_line_text = getRandomLine('file.txt');
console.log(the_random_line_text);
注意:因为现在这会阻塞主线程,如果您正在读取非常大的文件,请小心,这可能会导致问题。如果您确实使用了一个非常大的文件,我建议您在程序启动时将其作为数组加载,并仅引用该数组,而不是每次需要时都读取文件。
【讨论】:
我找到了一个更简单的方法。
fs = require('fs')
var data;
fs.readFile('filename.txt', 'utf8', function (err,rawData) {
if (err) {
return console.log(err);
}
data = rawData.split('\n');
});
function randomInt (low, high) {
return Math.floor(Math.random() * (high - low) + low);
}
function getRandomLine(){
return data[randomInt(0,data.length)];
}
如果您尝试在命令中发送消息。
message.channel.send(getRandomLine())
把它放在你的命令中。
把“filename.txt”改成你的名字,保持“utf8”不变。
注意:适用于大文件。
【讨论】: