-1

I am trying to be able to get value of the variable jsCss outside of the foreach and the readdir function. I can't seem figure it out. I tried to push it to a global variable but that still returned a empty array when I logged the array I pushed to. How would I go about doing this?

let items = [];

fs.readdir('.', (err, files) => {
    const readable = files.filter((el) => /\.vide$/.test(el));
    readable.forEach((script) => {
        let data = fs.readFileSync(script, { encoding: 'utf8' });
        const dom = htmlparser2.parseDOM(data);
        const $ = cheerio.load(dom);
        const CSS = $('Vide')
            .clone()
            .children()
            .remove()
            .end()
            .text();
        const str = css(CSS);
        let jsCss = JSON.parse(str);
        items.push(jsCss);
    })
});
console.log(items)
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek May 04 '20 at 16:52

1 Answers1

0

The console.log is executing earlier than items.push() thats why you see empty array

This should work as you expect


let items = [];

fs.readdir('.', (err, files) => {
    const readable = files.filter((el) => /\.vide$/.test(el));
    readable.forEach((script) => {
        let data = fs.readFileSync(script, { encoding: 'utf8' });
        const dom = htmlparser2.parseDOM(data);
        const $ = cheerio.load(dom);
        const CSS = $('Vide')
            .clone()
            .children()
            .remove()
            .end() //again go back to selected element
            .text();
        const str = css(CSS);
        let jsCss = JSON.parse(str);
        items.push(jsCss);
    });
    console.log(items);
});

Also you can use readdirSync() to omit callback like this:

let items = [];
const files = fs.readdirSync('.');
const readable = files.filter((el) => /\.vide$/.test(el));
readable.forEach((script) => {
    let data = fs.readFileSync(script, { encoding: 'utf8' });
    const dom = htmlparser2.parseDOM(data);
    const $ = cheerio.load(dom);
    const CSS = $('Vide')
        .clone()
        .children()
        .remove()
        .end() //again go back to selected element
        .text();
    const str = css(CSS);
    let jsCss = JSON.parse(str);
    items.push(jsCss);
});
console.log(items);
Damian Plewa
  • 1,123
  • 7
  • 13