Skip to content

Instantly share code, notes, and snippets.

@adam-lynch
Last active August 29, 2015 13:59
Show Gist options
  • Save adam-lynch/10480828 to your computer and use it in GitHub Desktop.
Save adam-lynch/10480828 to your computer and use it in GitHub Desktop.
Duck punching Gulp into waiting for something asynchronous. Example: Varying pipelines / tasks based on the contents of an external file.
/*
* Example: productionMode.txt contains either 0 or 1
*/
var productionMode = true; //defaults to production, don't change this
var gulp = require('gulp');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
// duck punching
var originalGulpStart = gulp.start;
gulp.start = function(args){
var startArgs = arguments,
self = this;
fs.readFile('./productionMode.txt', function(err, data){
if(err) throw new Error('error reading dev mode file');
productionMode = data.toString() === '1';
originalGulpStart.apply(self, startArgs);
});
};
// tasks
gulp.task('default', 'scripts');
gulp.task('scripts', function(){
gulp.src('./src/*.js')
.pipe(concat('script.js'))
.pipe(productionMode ? uglify() : gutil.noop()) // only minifies in production mode
.pipe(gulp.dest('./output');
});
@yocontra
Copy link

Why wouldn't you just do this?

var gulp = require('gulp');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var uglify = require('gulp-concat');
var fs = require('fs');

var productionTxt = fs.readFileSync('./productionMode.txt', 'utf8');
var productionMode = productionTxt === '1';


// tasks

gulp.task('default', ['scripts']);

gulp.task('scripts', function(){
    return gulp.src('./src/*.js')
        .pipe(concat('script.js'))
        .pipe(productionMode ? uglify() : gutil.noop()) // only minifies in production mode
        .pipe(gulp.dest('./output');
});

@adam-lynch
Copy link
Author

Thanks @contra. I guess because I never heard of readFileSync :). I've only began to really get into Node lately. Even my use case for this was to read a file written in a different server-side language. This would still stand though for async stuff in general though, right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment