[英]JSON variable not retrieving updated value
我正在尝试发布从JSON文件检索的报价。 我的代码每20秒发布一条推文(出于测试目的,这是20秒)。 我可以使用server(quoteIndex)
函数找到报价并将其放在JSON文件中。 server(quoteIndex)
将一个新的报价添加到我的output.json
文件中。 我知道output.json
每次在偶数索引上找到引号时都会更新{"quote": ""}
部分。 但是,在我的tweetIt()
函数中,当我分配var quoteFile = require("./output.json")
,我的quoteFile.quote
值不会更新。 这是一个问题,因为我的javascript机器人是推特引用的Twitter机器人。 Twitter不允许重复的引号,这给我一个“重复的状态”错误。
这是主要代码
// I wanted to start at the 8th index and continue with every even index.
var quoteIndex = 8;
// post a tweet every 20 seconds
setInterval(tweetIt, 1000*20);
tweetIt()
function tweetIt() {
//
// This will start looking for quotes to post
// It will put the quote in a JSON file
//
quoteIndex = quoteIndex + 2;
console.log('value of index: ' + quoteIndex)
server(quoteIndex);
var js = require('json-update');
js.load('./output.json', function(err, obj) {
console.log("Loaded from json:");
console.log(obj); // loads most recent quote
}); // this is what I want to tweet
var quoteFile = require('./output.json');
// Read from JSON file for the quote
var params = {
status: quoteFile.quote
}
//
// prints same quote each time, does not update
//
console.log("quote to tweet: " + quoteFile.quote)
// tweet a quote
//
// The first quote will tweet, however when the JSON file
// updates, I will get a "duplicate status" error.
// This is because my quoteFile still has not updated.
//
T.post('statuses/update', params, getData);
function getData(err, data, response) {
if (err) {
console.log("Something went wrong!: " + err);
} else {
console.log("Tweeted something!");
}
}
}
服务器(quoteNumber)
function server(quoteNumber) {
var fs = require('fs');
var request = require("request"),
cheerio = require("cheerio"),
url = "https://en.wikiquote.org/wiki/A_Song_of_Ice_and_Fire";
request(url, function (error, response, body) {
if (!error) {
var $ = cheerio.load(body);
var quote;
var json = {quote : ""};
$( "div.mw-parser-output ul" ).filter(function( INDEX ) {
// even indexed quotes are the ones I want
if (INDEX % 2 == 0 && (INDEX == quoteNumber)) {
quote = $( this ).text();
json.quote = quote; // this also has the most recent quote
}
});
} else {
console.log("We’ve encountered an error: " + error);
}
//
// Write our quotes out to a JSON file.
//
fs.writeFile('output.json', JSON.stringify(json, null, 4).replace(/\\n/g, " "), function(err){
console.log('File successfully written! - Check your project directory for the output.json file');
})
});
基本上,当我使用node.js运行代码时,第一个引号会鸣叫,因为JSON文件为我提供了一个引号。 然后,当需要使用quoteIndex = quoteIndex + 2
查找下一个报价时,我的JSON文件将按预期在项目文件夹中更新。 我的主要问题是在我的tweetIt()
函数中,即使JSON文件对我来说, quoteFile.quote
也不显示更新的报价。 如何获得最新报价?
任何提示将不胜感激,谢谢。
无论何时require()
文件require()
无论是模块文件还是JSON文件或本机插件),文件都将在成功加载后被缓存。 如果您需要能够重新加载JSON文件,则应该每次仅手动调用readFile()
和JSON.parse()
生成的文件数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.