1
\$\begingroup\$

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).

\$\endgroup\$
2
  • \$\begingroup\$ Can you not simply require your tasks\process.js and do a straight forward function call? See this: gruntjs.com/api/grunt.task#loading-externally-defined-tasks \$\endgroup\$
    – konijn
    Aug 25, 2014 at 15:08
  • \$\begingroup\$ @konijn The link you provided describes a .loadTasks() function which I already use to load my externally defined task into Grunt. This enables referencing the task by name; see 'process:auto' in my first code block above. *** If I required my code manually, where would I call it from? The only place I can think of is from within the "watch" event handler. However, the docs recommend against this practice. Read here: github.com/gruntjs/grunt-contrib-watch#using-the-watch-event \$\endgroup\$ Aug 25, 2014 at 19:48

1 Answer 1

1
\$\begingroup\$

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.