35

I have a gulp task that needs to read a file into a variable, and then use its content as input for a different function that runs on the files in the pipe. How do I do that?

Example psuedo-psuedo-code

gulp.task('doSometing', function() {
  var fileContent=getFileContent("path/to/file.something"); //How?

  return gulp.src(dirs.src + '/templates/*.html')
    .pipe(myFunction(fileContent))
    .pipe(gulp.dest('destination/path));
});
OpherV
  • 6,787
  • 6
  • 36
  • 55

2 Answers2

38

Thargor pointed me out in the right direction:

gulp.task('doSomething', function() {
  var fileContent = fs.readFileSync("path/to/file.something", "utf8");

  return gulp.src(dirs.src + '/templates/*.html')
    .pipe(myFunction(fileContent))
    .pipe(gulp.dest('destination/path'));
});
OpherV
  • 6,787
  • 6
  • 36
  • 55
  • 2
    what does myFunction return exactly? a stream? – Ayyash Oct 04 '16 at 18:27
  • @Ayyash it's complicated. In gulp you return a readable stream, usually with `through` a JavaScript library. This stream has some `Vinyl` virtual files it outputs. I recommend looking at a simple gulp plugin to see how it works. It's important to end any streams created and to call the end callbacks in your pipe handler functions if you make your own. – Bjorn Dec 31 '16 at 19:17
36

Is this what you're looking for?

fs = require("fs"),

gulp.task('doSometing', function() {

  return gulp.src(dirs.src + '/templates/*.html')
    .pipe(fs.readFile("path/to/file.something", "utf-8", function(err, _data) {
      //do something with your data
    }))
   .pipe(gulp.dest('destination/path'));
  });
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
Thargor
  • 709
  • 5
  • 19