Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJS – Returning 'undefined'

I am learning NodeJS (generally I write in PHP). Please help me figure out the Promises. Now the ‘getDataFromDir’ function returns ‘undefined’. I read the documentation, but apparently I don’t fully understand something. Thanks in advance!

const host = 'localhost';
const port = 3000;
const __dirname = process.cwd();

async function getDataFromDir(fileName){
    fsp
        .readdir(path.join(fileName))
        .then(async (indir) => {
            const list = []
            for (const item of indir) {
                const src = await fsp.stat(path.join(fileName, item))
                list.push(item)
            }
            return list;
        })
}

const server = http.createServer(async (req, res) => {
    const result = await getDataFromDir(__dirname);
    result
        .then((list) => {
            console.log(list);
    });
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It seems like your return statement is returning only for the callback function under your .then statement. You should be able to use the await statement with your initial request and achieve a similar result.

async function getDataFromDir(fileName){
    let indir = await fsp.readdir(path.join(fileName));
    const list = [];
    for (const item of indir) {
        const src = await fsp.stat(path.join(fileName, item));
        list.push(item);
    }
    return list;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading