Javascript Gulp:如何将文件内容读入变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29770191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:57:02  来源:igfitidea点击:

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

javascriptgulp

提问by OpherV

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?

我有一个 gulp 任务,需要将文件读入变量,然后将其内容用作在管道中的文件上运行的不同函数的输入。我怎么做?

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

回答by OpherV

Thargor pointed me out in the right direction:

Thargor 向我指出了正确的方向:

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

回答by Thargor

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