我的节点js模块函数返回undefined

时间:2017-08-22 01:18:23

标签: javascript node.js

我正在尝试创建一个模块,使用fs返回目录中的文件列表。 console.log按预期返回文件数组,但最后返回的对象未定义。有人可以向我解释一下。

模块:

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
}

1 个答案:

答案 0 :(得分:0)

节点js readdir方法是异步的:https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback

return files行放在回调函数内的for循环之后,你应该可以访问那里的文件对象。