Fixing empty files with grunt-typescript

I recently faced the problem of an empty app.js file while working with gulp and the typescript compiler, which was wrapped using the grunt-typescript module.




Synopsis: Almost every third or fourth call, the concatenated app.js was empty at the time where other gulp-tasks where running. The dependencies where all fine, and the gulp-output showed that the typescript-Task has successfully completed before the dependent task was started. However, the file was empty a the moment the dependent task tried to do anything with it.



As you can see, the build:ts and even the build-task has completed without errors.

Solution: After hours of work (debugging grunt-plugins is a pain), I found a solution which helped to actually wait for the particular file to exist or has its contents written to it.

Its a simple task, which I have added to the chain of tasks immediately before the task which actually needs the missing file to exist

var fs = require("fs")                 // Load the filesystem module  
    through = require('through2');

gulp.task('wait:tsbuild', ['build', 'clean:dist'], function() {

    var fileName = './build/.tmp/js/app.js';
    var timeOut = 10;
    var interval = 100;

    var amountWaited = 0;

    var waitForCompleteness = function waitForFileExistence(chunk, enc, cb) {

        var isFullfilled = false;

        try {
            var stats = fs.statSync(fileName);
            var fileSizeInBytes = stats["size"];

            isFullfilled = fileSizeInBytes > 0;
            //console.info('Dependency on file is:', isFullfilled, 'Size is: ', fileSizeInBytes);
        }
        catch(e) {}
        finally {}

        if (isFullfilled) {
            cb(null, chunk)
        }
        else if(amountWaited < timeOut) {
            amountWaited+=interval;
            setTimeout(waitForCompleteness, interval, chunk, enc, cb);
        }
        else {
            throw "Timed out while waiting for file '" + fileName + "'";            
        }
    }

   return gulp.src('./gulpfile.js').pipe(through.obj(waitForCompleteness ));
});
This is very ugly but helped me to work with the grunt-typescript plugin in an efficient way. A related issue can also be found in GitHub (although the newer version still does't work as expected): https://github.com/ivogabe/gulp-typescript/issues/245

Comments

Popular posts from this blog

Home Assistant in Docker with Nginx and Let's Encrypt on Raspberry Pi

Migrating from Arduino IDE to Visual Studio Code to PlatformIO

Use Bodmer TFT_eSPI Library with PlatformIO