簡體   English   中英

如何在帶有XML2js的Node.js中使用函數回調

[英]How to use function callbacks in Nodejs with xml2js

我正在使用xml2js來解析Nodejs中的XML文檔。

XML文件是遠程托管的,因此我使用Node.js http請求來獲取xml數據,然后使用xml2js對其進行解析,如下所示:

var parser = new xml2js.Parser();

function getValue(){
    var options = {
      hostname: myHost,
      path: myPath,
      method: 'GET',
      headers: {
          'Authorization': myAuthString
      }
    };

    var req = http.request(options, function(res) {
      res.on('data', function (response) {
        parser.parseString(response); 
      });
    });
    req.end();
}
parser.on('end', function(result) {
    // Output the distribution plans to console
     eyes.inspect(result);
     // Get the value that I want to use
     var returnThis = result['myKey'];
});

上面的代碼有效,當http請求接收到“ data”事件時,我獲取XML數據,然后xml2js解析器解析XML,並在解析的“ end”事件中獲取數據。

我的問題是,如何使用回調將“ returnThis”變量值返回給getValue函數?

例如,如果我要從XML中檢索人名,則希望此方法有效:

console.log("The returned name is: " + getValue());

任何建議將不勝感激! TIA!

請嘗試以下操作:

function getValue(callback){
    var options = {
      hostname: myHost,
      path: myPath,
      method: 'GET',
      headers: {
          'Authorization': myAuthString
      }
    };

    var req = http.request(options, function(res) {
      var parser = new xml2js.Parser();
      parser.on('end', function(result) {
        // Output the distribution plans to console
        eyes.inspect(result);
        callback(null, result['myKey'])
      });
      res.on('data', function (response) {
        parser.parseString(response); 
      });
    });
    req.end();
}

要使用您的函數,您將需要像這樣調用您的函數:

getValue(function(err, res){
  // res should equal myKey
  console.log(res)

})

事件示例

var emitter = require('events').EventEmitter,
    parseEmitter = new emitter();
function getValue(trigger){
    var options = {
      hostname: myHost,
      path: myPath,
      method: 'GET',
      headers: {
          'Authorization': myAuthString
      }
    };

    var req = http.request(options, function(res) {
      var parser = new xml2js.Parser();
      parser.on('end', function(result) {
        // Output the distribution plans to console
        eyes.inspect(result);
        callback(null, result['myKey'])
      });
      res.on('data', function (response) {
        parser.parseString(response); 
      });
    });
    parser.on('end', function(result) {
      // Output the distribution plans to console
      eyes.inspect(result);
      // Get the value that I want to use
      var returnThis = result['myKey'];
      trigger.emit('log', returnThis);
    });
    req.end();
}
parseEmitter.on('log', function(value) {
  console.log('The return name is '+value);
}
getValue(parseEmitter);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM