NodeJS ...将JSON保存到变量

Fin*_*n C 2 javascript json require node.js

我是NodeJS的新手,但是到处都是,似乎无法在下面找到解决问题的方法。我敢肯定这很简单,但是在此先感谢您能为我提供的所有帮助!

我正在尝试通过NodeJS创建一个简单的JSON刮板。我只需要将JSON存储到变量中即可。问题是,我使用的是Require,而他们的示例只是将其记录到控制台。我已经尝试在将变量记录到控制台后添加一个变量,但是我只是未定义。这是我的下面的代码,到目前为止还很简单:)

//  var jsonVariable; Doesn't work, shown as a test
function getJSON(url){
    var request = require("request")

    request({
    url: url,
    json: true
}, function (error, response, body) {

    if (!error && response.statusCode === 200) {
        console.log(body) // Print the json response
        //return body;  This doesn't work, nor does making a global variable called json and assigning it here. Any ideas?
        //jsonVariable = body; // This also doesn't work, returning undefined even after I've called the function with valid JSON
    }
})
}
Run Code Online (Sandbox Code Playgroud)

再次感谢您为我提供的任何帮助:)

Mat*_*ins 5

问题在于该request方法是异步的,但是您正在尝试同步返回结果。您将需要发出一个同步请求(使用的request包似乎无法实现),或者传递一个回调函数,以在请求成功响应时被调用。例如:

var request = require("request")

function getJSON(url, callback) {
  request({
    url: url,
    json: true
  }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      callback(body);
    }
  });
}

getJSON('http://example.com/foo.json', function (body) {
  console.log('we have the body!', body);
});
Run Code Online (Sandbox Code Playgroud)