gulpgulp-plugin

gulp inject relative file paths


I have a file, testboot.js, that I want to inject import statements like so:

import "../app/app.spec";
import "../app/navbar/navbar.spec";

Note that the import statement is relative to testboot.js. I am having trouble figuring out a clean way of doing this using gulp. Here is my partial gulp task:

gulp.task("inject", function (cb) {
    gulp
        .src("src/client/app/**/*.spec.js")
        .pipe(debug())
        .pipe(filenames("inject"))
        .on("end", function () {
            filenames.get("inject").map(function(e){
                // do something
            });
            util.log("in end"); // never called
            cb();
        });
});

But the "end" handler is never called. Can anyone help me out with this problem? Thank you.


Solution

  • You're listening for the wrong event. From the Node.js documentation on Stream:

    The 'finish' and 'end' events are from the parent Writable and Readable classes respectively. The 'finish' event is fired after stream.end() is called and all chunks have been processed by stream._transform(), 'end' is fired after all data has been output which is after the callback in stream._flush() has been called.

    That means you either have to listen for the 'finish' event:

    gulp.task("inject", function (cb) {
      gulp
        .src("src/client/app/**/*.spec.js")
        .pipe(debug())
        .pipe(filenames("inject"))
        .on("finish", function () {
            filenames.get("inject").map(function(e){
                // do something
            });
            util.log("in end");
            cb();
        });
    });
    

    Or you have to ensure that the callback in stream._flush() is invoked, e.g. with gulp.dest():

    gulp.task("inject", function (cb) {
      gulp
        .src("src/client/app/**/*.spec.js")
        .pipe(debug())
        .pipe(filenames("inject"))
        .pipe(gulp.dest('dist'))
        .on("end", function () {
            filenames.get("inject").map(function(e){
                // do something
            });
            util.log("in end");
            cb();
        });
    });