0

I want to return the files of a directory.

I need it to pass the route to another function.

In other words, how can I return the files of a directory using JavaScript/Node.js?

const fs = require('fs');
const path = require('path');
const mdLinks = require('../index');
exports.extension = (route) => {

    return new Promise((resolve, reject) => {
        try {
            recursive(route);
        } catch (e) {
            reject(e);
        }
    });
}

const recursive = (route) => {
    const extMd = ".md";
    let extName = path.extname(route);
    let files = [];
    fs.stat(route, (err, stats) => {
        if (stats && stats.isDirectory()) {
            fs.readdir(route, (err, files) => {
                files.forEach(file => {
                    let reFile = path.join(route, file);
                    if (file !== '.git') {
                        recursive(reFile);
                    }
                });
            })
        }
        else if (stats.isFile() && (extMd == extName)) {
            files.push(route);
        }

    })

    return files;
}
3
  • 1
    what is your not doing that it should do - or what errors do you see? Commented Sep 3, 2018 at 2:07
  • it would appear that files found inside recursive calls are lost, due to the way you have defined the files[] variable. Commented Sep 3, 2018 at 2:10
  • returns an empty array :( Commented Sep 3, 2018 at 2:34

1 Answer 1

1

There are multiple problems.

First off, your function is asynchronous so it cannot just return the files value because your function returns long before anything is added to the files array (that's one reason that it's empty). It will have to either call a callback when its done or return a promise that the caller can use. You will have to fix that in both the top level and when you call yourself recursively.

Second, you are redefining files at each recursive step so you have no way to collect them all. You can either pass in the array to add to or you can define the files array at a higher level where everyone refers to the same one or you can have the call to recursive concat the files that are returned to your current array.

Third, you haven't implemented any error handling on any of your asynchronous file I/O calls.

Here's my recommended way of solving all these issue:

exports.extension = (route) => {
    return recursive(route);
}

const util = require('util');
const stat = util.promisify(fs.stat);
const readdir = util.promisify(fs.readdir);

// returns a promise that resolves to an array of files
async function recursive(route) {
    const extMd = ".md";
    let extName = path.extname(route);
    let files = [];
    let stats = await stat(route);
    if (stats.isDirectory()) {
        let dirList = await readdir(route);
        for (const file of dirList) {
            if (file !== '.git') {
                let reFile = path.join(route, file);
                let newFiles = await recursive(reFile);
                // add files onto the end of our list
                files.push(...newFiles);
            }
        }
    } else if (stats.isFile() && extMd === extName) {
        files.push(route);
    }     
    // make the files array be the resolved value
    return files;
});
Sign up to request clarification or add additional context in comments.

1 Comment

@AndreaMonroy - I just fixed a couple typos so make sure you start with the latest code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.