diff --git a/README.md b/README.md index 37f2c65..d36536f 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,15 @@ b.transform(envify({ })) ``` +## Throw or Warn if env variable is missing ## + +May be you want to be sure, that all `process.env` were replaced. There is two +additional subargs to help you with that: `error` and `warn`. + +You can use it in the same way as `purge` subarg. + +Keep in mind that `purge`, `error` and `warn` are mutual exclusive. + ## Contributors ## * [hughsk](http://github.com/hughsk) diff --git a/test.js b/test.js index 8ed7ed3..c045957 100644 --- a/test.js +++ b/test.js @@ -153,3 +153,39 @@ test('-t [ envify purge --argument ]', function(t) { , 'var y = process.env.argument' ].join('\n')) }) + +test('-t [ envify error ]', function(t) { + var stream = envify() + var buffer = '' + var caughtError = false; + + stream(__filename, { _: ['error'] }) + .on('data', function(d) { buffer += d }) + .on('error', function (e) { + t.ok(e, 'throws error if env variable is missing'); + t.end(); + }) + .on('end', function () { + t.fail('should throw error if env variable is missing') + t.end(); + }) + .end('var x = process.env.MISSING_VAR') +}) + +test('-t [ envify error --argument]', function(t) { + var stream = envify() + var buffer = '' + var caughtError = false; + + stream(__filename, { _: ['error'], argument: 1 }) + .on('data', function(d) { buffer += d }) + .on('error', function (e) { + t.fail(e, 'should not throw if env variable is defined'); + t.end(); + }) + .on('end', function () { + t.pass('does not throw error if env variable is defined') + t.end(); + }) + .end('var x = process.env.argument') +}) diff --git a/visitors.js b/visitors.js index 4abff9f..06a576a 100644 --- a/visitors.js +++ b/visitors.js @@ -1,9 +1,12 @@ var Syntax = require('jstransform').Syntax var utils = require('jstransform/src/utils') +var util = require('util') function create(envs) { var args = [].concat(envs[0]._ || []).concat(envs[1]._ || []) var purge = args.indexOf('purge') !== -1 + var error = args.indexOf('error') !== -1 + var warn = args.indexOf('warn') !== -1 function visitProcessEnv(traverse, node, path, state) { var key = node.property.name @@ -18,6 +21,10 @@ function create(envs) { if (purge) { replaceEnv(node, state, undefined) + } else if (error || warn) { + var msg = util.format('envify did not find value for "%s" variable', node.property.name); + if(error) throw new Error(msg); + else console.log('WARN: ', msg); } return false