January 7, 2016

grunt.file.match and grunt.file.isMatch Do Not Access File System

Filed under: JavaScript, Software Blog — marcstober @ 10:05 am

While trying to improve my team’s grunt scripts, I spent a while stuck trying to figure out why grunt.file.isMatch wasn’t working.

I was expecting this to be like a fancy “file exists” check, that would take some pattern and looking in the current directory and subdirectories (as specified by my globbing pattern) to tell me if the file exists. And I couldn’t figure it out, especially since there were two arguments, “patterns” and “filepaths”.

Ultimately, I looked at the source code and figured out I’d gotten in all wrong. Despite being methods of the file object, “match” and “isMatch” don’t look at anything in the file system. They’re just string pattern matching operations: completely deterministic functions that match “patterns” against”filepaths”.

What I’d really wanted to do was something like:

if (grunt.file.expand(“my-dir/**/*.js”).length > 0) { …

Posting this so hopefully the next person searching the web for a solution to the same problem finds this and doesn’t get stuck like I did!