Gulp: How do I read file content into a variable?

2019-01-17 15:01发布

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));
});

2条回答
手持菜刀,她持情操
2楼-- · 2019-01-17 15:14

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'));
});
查看更多
叼着烟拽天下
3楼-- · 2019-01-17 15:30

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'));
  });
查看更多
登录 后发表回答