NodeJS读取文件,进行node-rest-client调用以获取相关数据,并将检索到的响应添加为JSON中的元素

时间:2017-09-25 17:34:29

标签: node.js rest node-rest-client

我正在使用fs.readFileSync读取JSON文件,对于获得的每个文档,我正在使用client.post进行休息API调用。一旦得到响应,我想将收到的内容放入另一个JSON文件,该文件是输入JSON的副本,除了附加元素,即从client.post调用接收的数据。但是可能是因为client.post的异步性质,我无法添加元素来输出JSON。我是NodeJS的新手。你能帮助我,在我失踪的地方。以下是代码和数据

数据:

[
    {
        "ticker": "CLYD"
    },
    {
        "ticker": "EGH"
    } 
]

代码:

var fs = require('fs');
var Client = require('node-rest-client').Client;

var data = fs.readFileSync(__dirname + "/data/stocks.json", "utf8");  
processData(data);

function processData (data) {

    var obj = JSON.parse(data);

    for (j = 0; j < obj.length; j++) {

        obj[j].stockInformation = getValuesForTicker (obj[j].ticker.trim());

    }

    var jsonOutput = JSON.stringify(obj,null,'\t');
    fs.writeFileSync(__dirname + "/data/response.json", jsonOutput);

};

function getValuesForTicker (ticker) {

    /**
     * More details and samples at https://www.npmjs.com/package/node-rest-client
     */
    var client = new Client();
    var values;

    // set content-type header and data as json in args parameter
    var args = {
        data: { "ticker" : ticker},
        headers: { "Content-Type": "application/json", "Accept" : "application/json" }
    };

    var responseToRequest = client.post("https://url.providing.response.as.json.content/", args, function (data, response) {
//         parsed response body as js object
        values = JSON.parse(JSON.stringify(data)).price;
    });
    return values;

};

1 个答案:

答案 0 :(得分:0)

由于getValueForTicker对获取数据进行异步调用,因此一旦收到数据(或更好的承诺)就应调用回调,并且不返回结果(当前返回值undefined在分配值之前)

function getValuesForTicker (ticker, callback) {

    /**
     * More details and samples at https://www.npmjs.com/package/node-rest-client
     */
    return new Promise(function(resolve, reject) {

             var client = new Client();
             var values;

           // set content-type header and data as json in args parameter
            var args = {
              data: { "ticker" : ticker},
              headers: { "Content-Type": "application/json", "Accept" : "application/json" }
           };

          var responseToRequest = 
          client.post("https://url.providing.response.as.json.content/", args, function (data, response) {
         //         parsed response body as js object
             values = JSON.parse(JSON.stringify(data)).price;
             resolve(values)
        });

    };
})

要在异步调用完成后获取数据,您需要调用then函数,如下所示:

        getValuesForTicker(obj[j].ticker.trim())
        .then(function(val) {
             obj[j].stockInformation = val
        })

考虑到你是node.js的新手,很难得到。花点时间先了解回调和承诺。