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,627
  • 4
  • 33
  • 55
  • 20
    What I'm trying to do is exactly what is I asked about. The pipe sources will undergo some sort of transformation that is affected by the file I'm trying to read. Your assumption is wrong and quite frankly disappointing. If there's a specific part of the documentation you think is relevant to my question I'd appreciate if provide a link to it. Otherwise your comment is unhelpful and condescending. – OpherV Apr 21 '15 at 11:09
  • 2
    You're being strangely vague about the 'sort of transformation' :) Depending on the transformation there might be a gulp plugin that does exactly what you want. Ex, if you want to do a string replace in the file there's a gulp plugin for that. Without knowing what types of files you're working with (`.something`), or what `myfunction()` there might be a more Gulp-ish way to do this. – Brett DeWoody Apr 21 '15 at 15:34

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,627
  • 4
  • 33
  • 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
35

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
  • 121,071
  • 74
  • 369
  • 447
Thargor
  • 699
  • 5
  • 18