Is it possible to convert a gulp stream to a string?

I want to apply some tasks in a gulp stream and get an output string. I do not want to 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/'));

});
+4
source share
1 answer

You cannot returncontents from a file in a gulp stream. This is not possible because the stream is asynchronous, so the content is not yet available when you try to execute returnit from your function.

You must listen to the "data"event in the stream, and then do everything 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);
  });

});
+1
source

Source: https://habr.com/ru/post/1666091/


All Articles