How to fetch current filename that is being processed using gulp.src()

214 views Asked by At

I have to run certain gulp task over multiple json files in a folder but the task would fetch files different location based on the filename.

I am able to run the task by passing the filename as an argument in cmd but I want to automate the script so that it would get executed for all the files in the src location.

gulp.task("writeJSON", function() {
    dataObj = require("./src/data/" + argv["filename"] + ".json");
    dataObjKeysList = require("./src/data/stats/" + argv["filename"] + ".json");
    segregateData(dataObj, dataObjKeysList, tabspace, false);
    gulp
      .src("./src/metadata.html")
      .pipe(rename(argv["filename"] + ".html"))
      .pipe(gulp.dest("./src/output"));
  });

Any help would be greatly appreciated.

1

There are 1 answers

0
Sudharshan Reddyam On

I am able to resolve the above issue using node filestream. I found this useful article

Filewalker Source

Used the below utility function which take the directory path and callback as args.

  function filewalker(dir, done) {
      let results = [];

      fs.readdir(dir, function(err, list) {
          if (err) return done(err);

          var pending = list.length;

          if (!pending) return done(null, results);

          list.forEach(function(file){
              file = path.resolve(dir, file);

              fs.stat(file, function(err, stat){
                  // If directory, execute a recursive call
                  if (stat && stat.isDirectory()) {
                      // Add directory to array [comment if you need to remove the directories from the array]
                      results.push(file);

                      filewalker(file, function(err, res){
                          results = results.concat(res);
                          if (!--pending) done(null, results);
                      });
                  } else {
                      results.push(file);
                      if (!--pending) done(null, results);
                  }
              });
          });
      });
  };

Added the below execution in my gulp task

filewalker("./src/data/stats/" , function(err, dataFilesList){
        if(err){
            throw err;
        }
        dataFilesList.map((name) => {
            let fileName = path.basename(name); 
            fileName = fileName.split('.')[0];
            gutil.log('Generating ' + fileName + '.html file.');
       });
    });