2

I am looking to run a node command through my gruntfile. I just need to run:

node index.js

as the first task before any other tasks. I tried searching around but haven't found the answer. I believe it might be something simple but I am not sure how. Do I need to load in nmp tasks?

This is how my Gruntfile looks like:

"use strict";

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js'
      ],
      options: {
        jshintrc: '.jshintrc',
      },
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      tests: ['dist/*']
    },

    // Configuration to be run (and then tested).
    mustache_render: {
      json_data: {
        files: [
          {
            data: 'jsons/offer.json',
            template: 'offers.mustache',
            dest: 'dist/offers.html'
          },
          {
            data: 'jsons/profile.json',
            template: 'profile.mustache',
            dest: 'dist/profile.html'
          }
        ]
      }
    }
  });


  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-mustache-render');

  // Whenever the "test" task is run, first clean the "tmp" dir, then run this
  // plugin's task(s), then test the result.
  grunt.registerTask('default', ['clean', 'jshint', 'mustache_render']);


};

I want to run "node index.js" before the 'clean' task.

Blueboye
  • 1,374
  • 4
  • 24
  • 49

1 Answers1

7

The standard way of doing this is to use the grunt-run task.

Do:

npm install grunt-run --save-dev

And in your grunt file:

grunt.loadNpmTasks('grunt-run');

And then some config (from the documentation):

grunt.initConfig({
  run: {
    options: {
      // Task-specific options go here.
    },
    your_target: {
      cmd: 'node',
      args: [
        'index.js'
      ]
    }
  }
})

Then you change the task registration to be this:

grunt.registerTask('default', ['run', 'clean', 'jshint', 'mustache_render']);
Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
  • 3
    alternatively, `grunt-exec` is another plugin that can accomplish the same need – theaccordance Mar 29 '17 at 16:43
  • That's right. There are many ways to do this. I just proposed the one I am most familiar with. – Andrew Eisenberg Mar 29 '17 at 20:29
  • @AndrewEisenberg but where is your npm script invoked? I can see any npm script invoked through this run task. Is that inside index.js? If yes, could you please share the content. – Peter Nov 15 '17 at 05:22
  • 1
    Do you mean things like `npm install`, and `npm run my-task`, then this approach has nothing to do with that. The question is about how to run node scripts inside of grunt. npm is only required to download grunt and grunt-run. – Andrew Eisenberg Nov 15 '17 at 14:57