0

I am trying to create a key value pair which looks like this

{
    'static/default/js/index': './app_main/js/index.js',
    'static/default/js/util': './app_util/js/util.js'
}

with path of the output file as the key and the source as the value.

The problem is when I debug the script at loop where I am iterating through the directory I see the correct key value pair as expected. But when I try to view it outside the loop it returns an empty object. Here is how my directory structure looks like

enter image description here

And here is my code

var fs = require('fs');

var path = [
    {
        type: 'js',
        inputPath: [
            './app_util/js/',
            './app_main/js/'
        ],
        outputPath: 'dist/static/default/js'
    }
];

function getFilePath(path) {
    var out = {};
    path.forEach(obj => {
        obj.inputPath.forEach(dirNname =>{
            fs.readdir(dirNname, (err, fileNames) => {
                if (err) {
                    console.log(err); // eslint-disable-line no-console
                    return;
                }
                fileNames.forEach(fileName => {
                    out[obj.outputPath] = dirNname+fileName;    
                    console.log(out); // eslint-disable-line no-console
                });
            })
        })
    })
    return out;
}

var x = getFilePath(path);
//this returns an empty object
console.log(x); // eslint-disable-line no-console

Any ideas what I could be doing wrong? Feels like I am missing something simple

soum
  • 1,131
  • 3
  • 20
  • 47
  • I hope, forEach is not asynchronous. if it is async, you may need to use and attach promise handler. – Krishna Oct 02 '18 at 03:19
  • readdir is async, you can use readdirSync instead. Or handle the promise. – ngearing Oct 02 '18 at 03:21
  • @ngearing -- if I use readdirSync I get TypeError: "options" must be a string or an object at Object.fs.readdirSync (fs.js:943:11) – soum Oct 02 '18 at 03:29
  • 1
    Sure, readdirSync isnt a drop in replacement, it returns and array so you dont need the callback. eg. https://stackoverflow.com/questions/2727167/how-do-you-get-a-list-of-the-names-of-all-files-present-in-a-directory-in-node-j – ngearing Oct 02 '18 at 05:03

1 Answers1

1
var fs = require('fs');

var path = [
  {
    type: 'js',
    inputPath: [
      './app_util/js/',
      './app_main/js/'
    ],
    outputPath: 'dist/static/default/js'
  }
];

function getFilePath(path) {
  var out = {};
  path.forEach(obj => {
    obj.inputPath.forEach(dirNname => {

      var fileNames = fs.readdirSync(dirNname)
      fileNames.forEach(fileName => {
        out[obj.outputPath] = dirNname + fileName;
        console.log(out); // eslint-disable-line no-console
      });

    })
  })
  return out;
}

var x = getFilePath(path);
//this returns an empty object
console.log('final result is: ', x); // eslint-disable-line no-console

I used readdirSync. This works fine.

varatharajan
  • 229
  • 2
  • 15