How to pull a variable from fs.readFile?

How to pull a variable starting to use it outside the fs.readFile? (new to this)

const parser = new xml2js.Parser();

fs.readFile('data.xml', function (data) {
 parser.parseString(data, function (result) {
 var starting = ("" + result['index']['starting']);
})
})
April 7th 20 at 15:45
1 answer
April 7th 20 at 15:47
Can rewrite the code to async/await
const { parseStringPromise } = require('xml2js');
const fs = require('fs');
const { promisify } = require('util');

const readFile = promisify(fs.readFile);

(async () => {
 const data = await readFile('data.xml');
 const result = await parseStringPromise(data);
 const starting = ("" + result['index']['starting']);
 // your code
console.log(starting);
});

or
const parser = new xml2js.Parser();
let starting;

function runMyCode() {
 // your code
console.log(starting);
}

fs.readFile('data.xml', function (data) {
 parser.parseString(data, function (result) {
 starting = ("" + result['index']['starting']);
runMyCode();
})
})
let starting;

function runMyCode() {
console.log(starting);
}

fs.readFile('data.xml', function (data) {
 parser.parseString(data, function (result) {
 starting = ("" + result['index']['starting']);
runMyCode();
})
})

5e4d0ba9a5dbb323752947.png

If you use the code I sent, it all works
fs.readFile('data.xml', function (err, data) {
 parser.parseString(data, function (err, result) {
 let starting = ("" + result['index']['starting']);
console.log(starting)
})
})

5e4d0cffeccaa155264155.png - ava46 commented on April 7th 20 at 15:50

Find more questions by tags JavaScriptNode.jsVKontakteXML