0

I am using xml2js node module https://www.npmjs.com/package/xml2js

I am parsing XML data into JSON

But how do I get the value outside this function?

var parseString = require('xml2js').parseString;

// My XML Data
var xml = "<root>my xml data</root>"

// Function to parse xml to json
parseString(xml, function (err, result) {
    console.dir(result);
});

I am looking to get the parsed value result out of the function so that I can use it at different components?

const jsonOutput = result;

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
floss
  • 2,603
  • 2
  • 20
  • 37
  • Note, you accepted the below answer, but that will *not* work in m,any circumstances unless you can *guarantee* that the `parseString` callback will finish before you try to use `stringResult`. In many cases though, you won't have such a guarantee. Pleae read the duplicate post. It's more complicated, but it shows how you can handle this in a fool-proof way. – Carcigenicate Feb 08 '19 at 00:03

1 Answers1

1

If you want to get result outside your parseString function:

var stringResult;

parseString(xml, function (err, result) {
    console.dir(result);
    stringResult = result;
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 1
    Yes and no. Yes, this will get the results out of the function, but depending on how `stringResult` is accessed, it may not be set by the time it's used. – Carcigenicate Feb 07 '19 at 23:55
  • How should I fix it then @Carcigenicate? – Jack Bashford Feb 07 '19 at 23:56
  • 1
    That's what's explained in the duplicate. You could string callbacks or promises or a similar mechanism. – Carcigenicate Feb 07 '19 at 23:57
  • @Carcigenicate should I set a timeer before I move to next function? would that help? or should I check if there are any valid data before I use the `result` value? – floss Feb 08 '19 at 04:13