Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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

Problem courtesy of: Rebe

Solution

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
});
Solution courtesy of: icktoofay

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×