Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glob in Node.js and return only the match (no leading path)

I need to glob ./../path/to/files/**/*.txt but instead of receiving matches like this:

./../path/to/files/subdir/file.txt

I need the root stripped off:

subdir/file.txt

Presently, I have:

oldwd = process.cwd()
process.chdir(__dirname + "/../path/to/files")
glob.glob("**/*.txt", function (err, matches) {
  process.chdir(oldwd)
});

But it's a little ugly and also seems to have a race condition: sometimes the glob occurs on oldwd. So that has to go.

I am considering simply mapping over matches and stripping the leading path with string operations. Since glob returns matches with the dotdirs resolved, I would have to do the same to my search-and-replace string, I suppose. That's getting just messy enough that I wonder if there is a better (built-in or library?) way to handle this.

So, what is a nice, neat and correct way to glob in Node.js and just get the "matched" portion? JavaScript and CoffeeScript are both ok with me

like image 449
Rebe Avatar asked Dec 30 '11 06:12

Rebe


2 Answers

Try this:

var path = require('path');
var root = '/path/to/files';
glob.glob("**/*.txt", function(err, matches) {
    if(err) throw err;
    matches = matches.map(function(match) {
        return path.relative(root, match);
    });
    // use matches
});
like image 182
icktoofay Avatar answered Nov 19 '22 22:11

icktoofay


Pass in the the directory to the options and have all that mess taken care of by glob.

glob.glob("**/*.txt", {cwd: '../../wherever/'}, function(err, matches) {
    ...
});
like image 21
jon skulski Avatar answered Nov 19 '22 21:11

jon skulski