Daniel
Daniel

Reputation: 1582

Control flow in node.js streams

I'm writing a gulp.js task, that concats/uglify my javascripts into app.min.js, then when it finishes, I want to inject app.min.js into a script tag in my index.jade file.

So I was writing the next task, without really knowing how node.js control flow works... (I'm better with promises).

gulp.task('js-prod', function () {
return gulp.src(['js/main.js', 'js/**/*.js', 'dist/templates.js', '!js/**/*.spec.js'])
    .pipe(sourcemaps.init())
    .pipe(concat('app.min.js'))
    .pipe(gulp.dest('dist'))
    .pipe(ngAnnotate())
    .pipe(uglify({mangle: false}))
    .pipe(rename('app.min.js'))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist'))
    .on('end', function () {
        var target = gulp.src('./index.jade');
        var sources = gulp.src(['dist/app.min.js'], {read: false});
        return target.pipe(inject(sources)).pipe(gulp.dest('./'));
    });

});

It seems to work, but is it the right way? Will gulp.js take the right async-hint? the one from the 'end' event? Im promises it will be -->

return startBuildPromise().then(function(){return (injectFileScript()});

Upvotes: 1

Views: 368

Answers (1)

robrich
robrich

Reputation: 13205

Try this:

gulp.task('js-prod', function (cb) {
    gulp.src(['js/main.js', 'js/**/*.js', 'dist/templates.js', '!js/**/*.spec.js'])
        .pipe(sourcemaps.init())
        .pipe(concat('app.min.js'))
        .pipe(gulp.dest('dist'))
        .pipe(ngAnnotate())
        .pipe(uglify({mangle: false}))
        .pipe(rename('app.min.js'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('dist'))
        .on('end', function () {
            var target = gulp.src('./index.jade');
            var sources = gulp.src(['dist/app.min.js'], {read: false});
            target.pipe(inject(sources))
                .pipe(gulp.dest('./'))
                on('end', cb);
        });
    });
});

Note that gulp will run as soon as the on('end') event happens. Now we have an unclear scenario as two things are listening to on('end'). Should the target.pipe(inject).pipe(dest) run first or gulp's "start up the next task"? Using callbacks makes this more explicit, and thus easier to reason about. If ever you're unsure which comes first, use a callback ... and ensure you return nothing.

Upvotes: 2

Related Questions