node.jsgulpthrough2

Get JSON/String of through2 stream?


I have a bunch of zip files, each file contains a .config file.

I want to iterate each zip, unzip it, read the config file, and use that config file to upload the zip file somewhere.

gulp.task('deploy-zips', function () {
  const filter = config()[target].filter;

  return gulp.src([destination + '/' + filter])
    .pipe(deployZips());
});

This is the task entry point.

function deployZips() {
  return through({ objectMode: true }, function (zipFile, zipEncoding, zipCallback) {
    gutil.log(zipFile.path.split('\\').reverse()[0]);

    gulp.src(zipFile.path)
      .pipe(unzip({
        filter : function(entry){

          if (entry.type !== 'File') {
            return false;
          }

          return entry.path.indexOf('deploy-config.json') > -1;
        }
      }))
      .pipe(through({ objectMode: true }, function(configFile, configEncoding, uploadCallback){
          gutil.log(configFile.path); // Outputs the file name as deploy-config.json

          //????
          var config = JSON.parse(configFile);

          uploadCallback(null, configFile);
      }))
      .on('end', function() {
          zipCallback(null, zipCallback);
      })
      ;
  });

}

This seems to display all the zip files I'm after, and then it outputs the config file I want to look at. However at this point I'm baffled as to how I can parse the config file to get the config.

I've tried parsing the configFile, reading the file using fs.readFileSync(...)

But nothing seems to work. The config contains the credentials to upload to, so I need to read it and then use that to send it to S3 or where ever its configured for.


Solution

  • Change configFile to configFile.contents

    var config = JSON.parse(configFile.contents);

    See https://github.com/gulpjs/vinyl#file

    function deployZips() {
      return through({ objectMode: true }, function (zipFile, zipEncoding, zipCallback) {
        gutil.log(zipFile.path.split('\\').reverse()[0]);
    
        gulp.src(zipFile.path)
          .pipe(unzip({
            filter : function(entry){
    
              if (entry.type !== 'File') {
                return false;
              }
    
              return entry.path.indexOf('deploy-config.json') > -1;
            }
          }))
          .pipe(through({ objectMode: true }, function(configFile, configEncoding, uploadCallback){
              gutil.log(configFile.path); // Outputs the file name as deploy-config.json
    
              var config = JSON.parse(configFile.contents);
    
              uploadCallback(null, configFile);
          }))
          .on('end', function() {
              zipCallback(null, zipCallback);
          })
          ;
      });
    
    }