I kicked off a project tonight and had a bunch of HTML files I wanted to open. I thought to myself, this has happened more than once, why not fire off a quick Grunt task?
Let’s get this fired off:
1 2 3
$ npm init $ (... follow prompts) $ npm install -g grunt-cli grunt
We’ll need a the
open npm module. The other dependencies are baked into node.
$ npm install open --save
I decided to set up a couple basic options, to at least make it feel like a more modular task I could use elsewhere:
- A base filename to open (in this case,
- Firefox as the
opentask, so as to not bog down my Chrome windows
- A base path to start from (in this case, just using the current path)
Here’s the finalized
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
open = require('open') fs = require('fs') module.exports = (grunt) -> grunt.initConfig openFiles: options: filename: "index.html" appName: "Firefox" path: "./" grunt.registerMultiTask 'openFiles', 'open', -> options = @options() basePath = @data.toString() files = fs.readdirSync(basePath) for i of files continue unless files.hasOwnProperty(i) name = basePath + files[i] if fs.statSync(name).isDirectory() open(name + "/" + options.filename, options.appName) grunt.registerTask("default", "openFiles")
Pretty slick. All I need to do is type
grunt in the terminal, it checks to ensure what it’s trying to open is a directory, and then fires it up.
Since all of the directories were named similarly, I was able to follow a pretty standard pattern. Of course, we could set this up a little more elegantly, say, by using a conditional to make sure the files exist, a limit to how many files we want to open, etc.
This might be a one off use case, but just shows you how powerful (and easy) it can be to use Grunt to automate even more simple tasks.