I'm trying to refactor my code a bit to make it a little nicer to use. What I would like to do is take a Node callback and pass back the result or error as a JavaScript object. It appears the scoping rules are preventing me from doing this, so is there a somewhat straightforward way to do this or am I stuck inside of the callback (unless I do something funky like implementing Promises in JavaScript, which Google Search reveals is what all the cool kids are doing these days)?
I'm still not all that comfortable with JavaScript - I think there is probably an easier way to do this and I'm just not getting it because I haven't worked with it enough (I know with jQuery I can set 'this' within a promise to get access to my outer scope, for example, but I'm not sure how to do this with Node, or if I can).
/*
 * Retrieves the full list of only the files, excluding subdirectories, in the directory provided.
 *
 * Parameters:
 *   dir: The directory to get the file list from.
 *
 * Return: An object containing either an error message or the fileList as a String array.
 *   e.g.
 *   { errMsg: undefined,
 *     fileList: ["file1.txt", "file2.xlsx"]
 *   }
 */
var getFileList = function (dir) {
  var filterOutDirectories = function (files) {
        return files.map(function (file) {
          return path.join(dir, file);
        }).filter(function (file) {
          return fs.statSync(file).isFile();
        });
      };
  var result = {
    errMsg: null,
    fileList: null
  };
  fs.readdir(dir, function (err, files) {
    if (err) {
      result.errMsg = "Error: Could not retrieve files...\n\t" + err;
    } else {
      result.fileList = filterOutDirectories(files);
    }
  });
  console.log(result.fileList); // returns null
  console.log(result.errMsg); // also returns null
  return result;
}
 
    