1
\$\begingroup\$

Based on a set of globs contained in a custom field within a package.json file, I'm trying to get a list of all the files that the glob matches. In my continual quest to get more familiar with Bluebird, I've chosen to use it to facilitate this task. What I have works, but I'm not sure if I am using the methods as intended as I always find the docs a bit mystifying.

Is there a cleaner way to do this? Could I be using these methods better?

Sample of JSON prop containing globs. I am just attempting to match the files within the variableGlobs object.

"@me": {
   "singleGlob": "path/to/single/glob/*.txt",
   "variableGlobs": {
    "glob1": "path/to/files1/*",
    "glob1": "path/to/files2/*"
   }
}



var _ = require('lodash')
  , Promise = require('bluebird')
  , globAsync = Promise.promisify(require('glob'))

const npmScope = '@me';
const nodeBase = path.join(__dirname, 'node_modules', npmScope);

function getFilenamesFromJson(){
  componentStaticAssetGlobs = Promise.map(components, componentName => {
    return extractComponentPackageJsonValue(componentName, npmScope);
  })
  .then(componentsPackageJson => {
    return Promise.map(componentsPackageJson, (singlePackage, componentIndex) => {
      return Promise.map(Object.keys(singlePackage[npmScope].staticAssetGlobs), (staticAssetKey, assetIndex) => {
        return globAsync(path.join(nodeBase, componentsPackageJson[componentIndex].componentName, singlePackage[npmScope].staticAssetGlobs[staticAssetKey]));
      })
    })
  })
  .then(staticAssetFiles => {
    staticAssetFiles = _.flattenDeep(staticAssetFiles);
    console.log('staticAssetFiles', staticAssetFiles); //array of files
  });
}

//returns object that always has component name
function extractComponentPackageJsonValue(componentName, property) {
  let packageJsonLocation = path.join(nodeBase, componentName, 'package.json');
  return fs.readFileAsync(packageJsonLocation, 'utf8')
    .then(jsonData => {
      jsonData = JSON.parse(jsonData);
      var tempObj = {componentName: componentName};
      tempObj[property] = jsonData[property]
      return tempObj;
    });
}
\$\endgroup\$
  • \$\begingroup\$ Long variable names aid understanding but not readability. I think I would opt for shorter names and a few explanatory comments. \$\endgroup\$ – Roamer-1888 Dec 20 '16 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.