nodejs express fs iterating files into array or object failing

后端 未结 5 2256
我寻月下人不归
我寻月下人不归 2021-02-15 10:43

So Im trying to use the nodejs express FS module to iterate a directory in my app, store each filename in an array, which I can pass to my express view and iterate through the l

5条回答
  •  既然无缘
    2021-02-15 10:49

    The myfiles array is empty because the callback hasn't been called before you call console.log().

    You'll need to do something like:

    var fs = require('fs');
    fs.readdir('./myfiles/',function(err,files){
        if(err) throw err;
        files.forEach(function(file){
            // do something with each file HERE!
        });
     });
     // because trying to do something with files here won't work because
     // the callback hasn't fired yet.
    

    Remember, everything in node happens at the same time, in the sense that, unless you're doing your processing inside your callbacks, you cannot guarantee asynchronous functions have completed yet.

    One way around this problem for you would be to use an EventEmitter:

    var fs=require('fs'),
        EventEmitter=require('events').EventEmitter,
        filesEE=new EventEmitter(),
        myfiles=[];
    
    // this event will be called when all files have been added to myfiles
    filesEE.on('files_ready',function(){
      console.dir(myfiles);
    });
    
    // read all files from current directory
    fs.readdir('.',function(err,files){
      if(err) throw err;
      files.forEach(function(file){
        myfiles.push(file);
      });
      filesEE.emit('files_ready'); // trigger files_ready event
    });
    

提交回复
热议问题