如何使用 node.js 读取名词文本文件并将其存储在变量中
How can I use node.js to read a text file of nouns and store it in a variable
所以我正在尝试编写一个机器人,每小时 "You wouldn't (random verb) a (random noun), would you?" 向 Facebook 发帖。我有一长串名为 "verbs.txt" 和 "nouns.txt" 的动词和名词。我遇到的问题是让程序读取文件,从文件中选择一个随机词,并将其存储在一个变量中。我已经尝试了很多不同的东西,但没有结果,我已经将我的代码回溯到这个版本 运行,除了未定义的变量。
let postContents = "You wouldn't" + verb + " a " + noun + ", would you?";
FB.api('me/feed', 'post', { message: postContents }, res => {
if (!res || res.error) {
return console.error(!res ? 'error occurred' : res.error);
}
console.log(`Post ID: ${res.id}`);
});
假设文件如下所示:
noun
noun1
您可以这样加载它。这是同步的方式。如果需要,您也可以以异步方式执行此操作。
const fs = require("fs");
const nounFile = "nouns.txt";
const verbFile = "verbs.txt";
const readFile = function (file) {
return fs.readFileSync(file).toString().split("\n");
};
const randomItem = function (items) {
return items[Math.floor(Math.random() * items.length)];
};
const nouns = readFile(nounFile);
const verbs = readFile(verbFile);
const noun = randomItem(nouns);
const verb = randomItem(verbs);
所以我正在尝试编写一个机器人,每小时 "You wouldn't (random verb) a (random noun), would you?" 向 Facebook 发帖。我有一长串名为 "verbs.txt" 和 "nouns.txt" 的动词和名词。我遇到的问题是让程序读取文件,从文件中选择一个随机词,并将其存储在一个变量中。我已经尝试了很多不同的东西,但没有结果,我已经将我的代码回溯到这个版本 运行,除了未定义的变量。
let postContents = "You wouldn't" + verb + " a " + noun + ", would you?";
FB.api('me/feed', 'post', { message: postContents }, res => {
if (!res || res.error) {
return console.error(!res ? 'error occurred' : res.error);
}
console.log(`Post ID: ${res.id}`);
});
假设文件如下所示:
noun
noun1
您可以这样加载它。这是同步的方式。如果需要,您也可以以异步方式执行此操作。
const fs = require("fs");
const nounFile = "nouns.txt";
const verbFile = "verbs.txt";
const readFile = function (file) {
return fs.readFileSync(file).toString().split("\n");
};
const randomItem = function (items) {
return items[Math.floor(Math.random() * items.length)];
};
const nouns = readFile(nounFile);
const verbs = readFile(verbFile);
const noun = randomItem(nouns);
const verb = randomItem(verbs);