我想發佈從JSON文件檢索到的報價。我的代碼每20秒發佈一條推文(爲了測試目的,它是20秒)。我可以通過使用server(quoteIndex)
函數找到我的報價並將其放入JSON文件中。 server(quoteIndex)
爲我的output.json
文件添加了新的報價。我知道output.json
每次在偶數索引上找到引用時都會更新{"quote": ""}
部分。但是,在我的tweetIt()
函數中,當我指定var quoteFile = require("./output.json")
時,我的quoteFile.quote
值不更新。這是一個問題,因爲我的JavaScript機器人是推文引號的推特機器人。而且twitter不允許重複引號,給我一個「重複狀態」的錯誤。JSON變量不檢索更新值
這是主代碼
// 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');
})
});
BASICA lly,當我使用node.js運行代碼時,第一個引號會發送推文,因爲JSON文件對我有引用。然後,當使用quoteIndex = quoteIndex + 2
找到下一個報價時,我的JSON文件按預期在我的項目文件夾中更新。我的主要問題是,在我的tweetIt()
函數中,quoteFile.quote
未顯示更新的引用,即使JSON文件對我而言有更新的引用。我如何獲得更新的報價?
任何提示將不勝感激,謝謝。
我對如何執行'readFile()'感到困惑。我可以通過執行'fs.readFile('./ output.json',...)'來解決這個問題,但是其中的所有內容(引用數據),我都不能分配給我的'params'變量。 – hbhatt687
當然你可以,只需在回調中的'readFile()'調用下面放置所有的邏輯。如果你想堅持同步調用,那麼使用'readFileSync()'。 – mscdex