Search code examples
javascriptgulpbuild-process

Gulp task to delete empty files


When compiling TypeScript, I get a lot of empty JavaScript files generated because their TypeScript counterparts contain only interfaces. There's currently no tsc option to suppress generation of these files. I'm using the gulp-tsc plugin to compile.

Is there a plugin or some other means to clean up empty files, or even a more general purpose gulp plugin that would allow me to delete files based on their name and content? Or is there a way to do this in gulp without using plugins?


Solution

  • I think you could relatively easily use node-glob to look for matching files outside gulp, something like this:

    var glob = require('node-glob'),
        fs = require('fs);
    
    gulp.task('delete-empty-files', function(cb) {
        glob('/path/to/generated/**/*.js', function(err, files) {
            files.forEach(function(file) {
                if(fs.statSync(file).size === 0) {
                    fs.unlinkSync(file);
                }
            });
            // make sure the task runs asynchronously!
            cb();
        });
    });
    

    Alternatively, you could use gulp-tap to achieve a similar result, like so:

    var tap = require('gulp-tap'),
        fs = require('fs);
    
    gulp.task('delete-empty-files', function() {
        return gulp.src('/path/to/generated/**/*.js')
            .pipe(tap(function(file) {
                if(file.stat.size === 0) {
                    fs.unlinkSync(file);
                }
            });
        });
    });
    

    They're pretty equal, really. I think the first one will be faster, because it won't have the extra stuff from gulp and vinyl-fs.

    You might be able to add the {read: false} options to gulp.src() to speed things up, but that might also disable the .stat from being read. If you want to try it, you add it like this:

    return gulp.src('/path/to/files/**/*.js', {read: false}).pipe(...)