0

How can I use Node's debug module with Grunt?

I know that to use the module I need to set the DEBUG env var in the command line like so:

$ DEBUG=* node app.js

But, I am struggling to figure out how to do it with Grunt.

Xavi Gil
  • 11,460
  • 4
  • 56
  • 71
  • possible duplicate of http://stackoverflow.com/questions/11171013/using-node-inspector-with-grunt-tasks – Vishwanath Mar 12 '15 at 14:08
  • I don't want to run node in debug mode. I want to use the third party debug module. I just don't know how to set the DEBUG variable running Grunt instead of setting it in the command line. – Xavi Gil Mar 12 '15 at 15:07
  • So you want to use [debug-module](https://github.com/visionmedia/debug) in your grunt code? – Vishwanath Mar 12 '15 at 15:10
  • You mean `var debug = require('debug')` and `set DEBUG=*` on command line... – Vishwanath Mar 12 '15 at 15:16

1 Answers1

1

I used grunt-env to help set env variable in grunt as below:

grunt.loadNpmTasks('grunt-env');

// Define the configuration for all the tasks
grunt.initConfig({

  // Env-specific configuration
  env: {
    options: {
      //Shared Options Hash
    },
    dev: {
      NODE_ENV: 'development',
      DEBUG: 'wukong:*,loopback:security:role,-not_this'
    },
    test: {
      NODE_ENV: 'test',
      DEBUG: 'wukong:*,-not_this'
    }
  },
  // ...
}

However, it doesn't work because debug module load and save process.env.DEBUG at the very beginning of module initialization: https://github.com/visionmedia/debug/blob/master/node.js#L209

Thus, I played a trick to load the DEBUG variable again via its "hidden" public API - enable as:

const debug = require('debug');
debug.enable(process.env.DEBUG);
module.exports = debug;

When this debug wrapper is used instead, grunt could print out debug message as expected.

Hope this workaround works for you as well. ;)

zhanghaili
  • 141
  • 1
  • 3