-1

I am trying to create a module to return a list of files in directory using fs. The console.log returned array of files as expected but in the end returned object is undefined. Can somebody explain this to me.

the module:

exports.fileList = function () {
  var fs = require('fs');
  var path = require('path');
  var dirPath = 'C:/Users/Desktop/Hotkey';  //directory path
  var files = [];
  fs.readdir(dirPath, function(err,list){
    if(err) throw err;
    for(var i=0; i<list.length; i++){
      console.log(i + ':' + list[i]); //print the file
      files.push(list[i]); //store the file name into the array files
    }
    console.log(files); // array here is displayed correctly
  });

  return files; //return undefined object
}
froggy
  • 1
  • 2
  • how many files do you have? how many files does the array return? can you let us see them too? what does it log to the console? –  Aug 22 '17 at 01:20
  • `console.log(i + ':' + list[i]);` - how many times did that print in the for loop, and was it also printing undefined for the array values? – Pat Needham Aug 22 '17 at 01:22
  • 1
    It should return at least an empty array, not `undefined`. – Felix Kling Aug 22 '17 at 01:22
  • Thank you for the reply guys, I called the function using the code as follows: `var http = require('http'); var dl = require('./dirlist'); http.createServer(function (req, res) { var test = new Array(); test = dl.fileList(); console.log('test' + test); res.writeHead(200, {'Content-Type': 'text/html'}); res.write("The date and time are currently: " + test); res.end(); }).listen(3000);` – froggy Aug 22 '17 at 01:31
  • tthe output of the log is : `test 0:hotkey.bat 1:hotkeys.ahk 2:scripts 3:userMaintainance.sap [ 'hotkey.bat', 'hotkeys.ahk', 'scripts', 'userMaintainance.sap' ] ` and the html file output is: `The date and time are currently: undefined ` – froggy Aug 22 '17 at 01:37
  • `fs.readdir` is **asynchronous**, which is why you have to pass a callback to it. Either make your function accept a callback too (look at the duplicates), or use the synchronous version of `readdir`. – Felix Kling Aug 22 '17 at 01:37
  • @FelixKling, i see, i will check on the duplicates. thank you so much! – froggy Aug 22 '17 at 01:40

1 Answers1

0

The node js readdir method is asynchronous: https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback

Put the return files line right after the for loop inside the callback function and you should have access to the files object there.

Pat Needham
  • 5,698
  • 7
  • 43
  • 63