Z
Z
zonf1k2020-02-18 20:34:38
JavaScript
zonf1k, 2020-02-18 20:34:38

How to pull a variable from fs.readFile?

How can I pull out the starting variable so that it can be used outside of 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']);
    })
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolai Alexandrov, 2020-02-18
@dos

You 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();
    })
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question