Diego Rayo
Diego Rayo

Reputation: 85

Can I convert a gulp stream into a String?

I want to apply some tasks in a gulp stream and get the output string. I dont want create a new file.

This is my code:

function buildCSS() {

    // READ A FILE AND APPLY SOME TASKS
    var content = gulp.src(__dirname + '/src/styles.less')
        .pipe(g.less());

    if (environment === 'live') {
        content.pipe(g.minifyCss());
    }

    // I NEED RETURN A STRING
    return content;
}

gulp.task('build-html', function() {

  // I SHOULD GET THE CSS TEXT 
  var cssText = buildCSS(); 

  gulp.src(__dirname + '/src/template.html')
        // INSERT THE CSS IN A HTML FILE (REPLACE AS STRING)
        .pipe(g.replace('/*INJECT:CSS*/', cssText))
        .pipe(gulp.dest(__dirname + '/dist/'));

});

Upvotes: 4

Views: 2226

Answers (1)

Sven Schoenung
Sven Schoenung

Reputation: 30564

You cannot return the content from a file in a gulp stream. That's impossible because the stream is asynchronous so the content isn't even available yet when you try return it from your function.

You have to listen for the "data" event in the stream and then perform whatever you want to do in the event handler function:

gulp.task('build-html', function(cb) {

  buildCSS().on('data', function(file) {
    var cssText = file.contents.toString();
    gulp.src(__dirname + '/src/template.html')
      .pipe(g.replace('/*INJECT:CSS*/', cssText))
      .pipe(gulp.dest(__dirname + '/dist/'))
      .on('end', cb);
  });

});

Upvotes: 2

Related Questions