Home > front end >  How to wait for fs.readdir function execution? Node JS
How to wait for fs.readdir function execution? Node JS

Time:04-04

Code:

function getLocalFiles() {
    let files = [];
    return new Promise((resolve, reject) => {
        fs.readdir('storage', (err, filenames) => {
            if (err)
                throw err;
            filenames.forEach((filename) => {
                fs.readFile('storage/'   filename, 'utf-8', (err, data) => {
                    if (err)
                        throw err;
                    const file = {
                        filename: filename,
                        content: data
                    };
                    files.push(file);
                    //console.log(files); I checked that array has a files but then it returns empty
                });
            });
        });
        resolve(files);
    })
}

api.get('/', async (req, res) => {
    const files = await getLocalFiles();
    res.send('local files:\n'   files);
})

I have some files in "storage" directory and I declared a getLocalFiles() function that read the name and content of each file in this directory and pushed it to "files" array. But instead of this I got and empty array. Why files are not written to the array?

CodePudding user response:

A few pointers:

  1. The code you're writing would benefit a lot from using the promises version of fs (fs/promises).
  2. avoid mixing promises and callbacks, and just use promises (via async/await where possible).
  3. I didn't change it here, but if you're gonna be running this on windows, the / separator won't cut it, so use path.join('storage', filename) instead
const fs = require('fs/promises');

async function getLocalFiles() {
    let files = [];
    const dir = await fs.readdir('storage')
    for (const filename of dir) {
      files.push({
        filename,
        content: await fs.readFile('storage/'   filename, 'utf-8')
      })
    }
    return files;
}

api.get('/', async (req, res) => {
    const files = await getLocalFiles();
    res.send('local files:\n'   files);
})

  • Related