Sunday, 16 April 2017

Efficient function to create array of/from File Directory Structure

I have been working on a function which would take a relative directory name, recursively iterate through the directory and all its sub-directories, and create an array of the entire structure including the files.

I started with the work done here: https://gist.github.com/kethinov/6658166

I am developing for a standalone app and can take advantage of ES6/ES7.

The following code works. However, my main goal is to improve my coding skills so I am wondering if there is a better way? More efficient? More functional?

I know I can move the named function directly into the .map and use an arrow function but should I? In this case I am not really returning anything so is using the more concise syntax less clear? The fact that I am not explicitly returning and utilizing that return but rather relying on a side effect(?) is not functional.

const fs = require('fs');
const path = require('path');


function walkSync(dir, array = []) {

  function _process(collectionElement) {

    const nextJoin = path.join(dir, collectionElement);
    array.push(nextJoin.replace(/\\/g, '/'));

    if (fs.statSync(nextJoin).isDirectory()) {

      walkSync(nextJoin, array);

    }

  }

  fs.readdirSync(dir).map(_process);

  return array;

}

console.log(walkSync('directory'));



via Phillip Z

No comments:

Post a Comment