Reputation: 59
Is there a way to save data from an API to a JSON file, with NodeJS using XMLHttpRequest?
The API data is supposed to be displayed on a website, but the API is increcibly slow, so to combat this I would save the data on the server and display the newest data on the website every 5 minutes.
The API is public, the link is http://lonobox.com/api/index.php?id=100002519 if that helps.
Any help is greatly appreciated.
Upvotes: 1
Views: 1140
Reputation: 198
Hey I do a similar thing with a node server that performs basic function on JSON data that I use at work. When it comes to saving the data I just POST it to the server.
But when it come to reading the data I use a XMLHttpRequest to do it, let me illustrate how it works which should give you a good start.
POST file to server.
function processFile(e) {
var file = e.target.result,results;
if (file && file.length) {
$.ajax({
type: "POST",
url: "http://localhost:8080/",
data: {
'data': file
}
}).done(function(msg) {
appendText("Data Saved: " + msg);
});
}
}
From here you can fetch the data with XMLHttpRequest like so...
function getFile(){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "filename.json", false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var fileText = rawFile.responseText;
}
}
}
rawFile.send(null);
}
Server Code
app.post('/', function(req, res) {
var fileLoc = __dirname.split("\\").length > 1 ? __dirname + "\\public\\filename.json" : __dirname + "/public/filename.json";
fs.writeFile(fileLoc, req.body.data, function(err) {
if (err) {
res.send('Something when wrong: ' + err);
} else {
res.send('Saved!');
}
})
});
Server side requires FS and I use Express for routing.
Upvotes: 1