如何在带有 xml2js 的 Nodejs 中使用函数回调

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" 事件的数据。

我的问题是,如何使用回调将 return "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);