简体   繁体   中英

Saving a json file to the computer using The request module

I am an amateur in coding, so seeking help here. I am trying to request data from RescueTime using the Request module. -I have figured out how to get the Body of the data but couldn't find a way to write/save the JSON file to the local hard disk. Here's the JS snippet

var request = require("request");

request({ uri: "https://www.rescuetime.com/anapi/daily_summary_feed?key=MY_API_KEY", method: "GET" }, function(error, response, body) {
  var jsonfile = require('jsonfile')

  var file = '/Documents/request-playground/data.json'
  //Path on the local hard disk

  var obj = {name: 'JP'}

  jsonfile.writeFile(body, obj, {spaces: 2}, function(err) {
    console.error(err)
  })

});

It looks like you just copied the example from the npm page. If you want to write to file you need to make that the first parameter to writeFile . In the example the payload written to the file is obj , here it should be body .

This should do the trick for you:

var request = require("request");
var jsonfile = require('jsonfile');

request("https://www.rescuetime.com/anapi/daily_summary_feed?key=MY_API_KEY", function(error, response, body) {


  var file = '/Documents/request-playground/data.json'
  //Path on the local hard disk

  jsonfile.writeFile(file, body, {spaces: 2}, function(err) {
    console.error(err)
  })

});

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