Search code examples
javascriptexpressionworkflow

Return a list of files based on file extension with a javascript expression


I'm having trouble returning a list of files based on file extension and don't have enough experience with javascript to know the right syntax to accomplish this. The expression handles file.basename but not file.nameext, so I'm not sure how to effectively parse. This is to write a javascript expression in a Common Workflow Language expression tool, as part of a workflow.

Assuming the directory has .txt, .gz, and .gz.foo, I'd like to return a list of all the .gz files.

${
  var gzs = [];

  for (var i = 0; i < inputs.dir.listing.length; i++) {
    var file = inputs.dir.listing[i];
    if file.basename.match(".gz"); {
      gzs.push(file);
    }
  }

  return {
    "gzs": gzs
  };
}

Solution

  • You can split the file name using split and dot (.) as delimiter. This will give an array. In this array check for the last element. If that matches then put the file in the array.

    Secondly you are using a return statement but I cannot see a function. Put your code inside a function

    let inputs = {
      dir: {
        listing: ['abc.gz', 'def.sb', 'ghi.gz', 'jkl.er.km']
      }
    }
    
    function giveGzFile() {
      let gzs = [];
      for (var i = 0; i < inputs.dir.listing.length; i++) {
        var file = inputs.dir.listing[i];
        let splitedFileName = file.split('.');
        if (splitedFileName[splitedFileName.length - 1] === "gz") {
          gzs.push(file);
        }
      }
      return {
        "gzs": gzs
      };
    }
    console.log(giveGzFile())