Passing a value from my Gruntfile to an external Grunt task In my Gruntfile, I use the grunt-contrib-watch task to watch a directory for file changes:

watch: {
    releases: {
        files: ['source/md/releases/*.md'],
        tasks: ['process:auto']
    }
}


Also, in the Gruntfile, I have a "watch" event handler. Inside this handler, I temporarily store the file path of the file that was modified, so that my task can read this information and only process that file:

grunt.event.on('watch', function (action, filepath, target) {
    if (target === 'releases') {
        grunt.file.write('filepath.txt', filepath);
    }
});


Then, inside my Grunt task (which is located in "tasks/process.js"), I read that file:

if (this.target === 'auto') {
    path = grunt.file.read('filepath.txt');

    // process file at given path

    grunt.file.delete('filepath.txt'); // delete this temporary file
}




Having to share the file path information via a file certainly doesn't seem optimal, but I haven't found a better solution yet. Note that writing the file path information directly into the configuration of my task from within the "watch" handler:

grunt.config('process.auto.filepath', filepath);


only works with the spawn:false setting in the "watch" configuration. I cannot set this option because then there is a 10 second delay between "watch" events (i.e. file modifications are ignored in that period).
Since file is an object, and it has a constructor, that can be use to store the file path:

grunt.event.on('watch', function (action, filepath, target) {
    if (target === 'releases') {
        grunt.file.constructor.filepath = filepath;
    }
});


References


Why Composition is Harder with Classes – JavaScript Scene – Medium
grunt/file.js at master · gruntjs/grunt