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
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
});
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) {
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With