0

Let's say we have a directory that contains four folders, like so:

- folder-1
- folder-2
- folder-3
- folder-4

How can I get their path and store them in an array so I'd have an array like:

['root/parent/folder-1', 'root/parent/folder-2', 'root/parent/folder-3', 'root/parent/folder-4']
2
  • 1
    use the path module nodejs.org/api/path.html and please, tell us a bit more about the context, are you listing the current directory? Do you just happen to have an array of dir strings? Commented Mar 8, 2016 at 12:49
  • @cl3m Thanks, it may be the current directory and it may not, I don't have an array, I'm trying to create one based on directories name. Commented Mar 8, 2016 at 13:02

2 Answers 2

3

Do it this way if you don't need absolute path omit __dirname use dirPath:

var fs = require('fs');

var dirPath = 'parent/';
var result = []; //this is going to contain paths

fs.readdir(__dirname + dirPath, function (err, filesPath) {
    if (err) throw err;
    result = filesPath.map(function (filePath) {
        return dirPath + filePath;
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

You could do it through fs.readdir

var fs = require('fs');

fs.readdir('root/parent/', function(err, files) {
    if (err)
        console.log(err);
    else
        files.map(function(f) {
            return 'root/parent/'+f;
        });
        return files;
})

Comments

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.