简体   繁体   中英

Saving API data to JSON file with NodeJS (or PHP)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM