2016-03-06 32 views
1

使用node.js的fs模块读取目录中的所有文件并返回其内容,但用于存储内容的数组始终为空。返回node.js中多个文件的内容

服务器端:

app.get('/getCars', function(req, res){ 
    var path = __dirname + '/Cars/'; 
    var cars = []; 

    fs.readdir(path, function (err, data) { 
     if (err) throw err; 

     data.forEach(function(fileName){ 
      fs.readFile(path + fileName, 'utf8', function (err, data) { 
       if (err) throw err; 

       files.push(data); 
      }); 
     }); 
    }); 
    res.send(files); 
    console.log('complete'); 
}); 

AJAX功能:

$.ajax({ 
    type: 'GET', 
    url: '/getCars', 
    dataType: 'JSON', 
    contentType: 'application/json' 
}).done(function(response) { 
     console.log(response); 
}); 

在此先感谢。

+0

你做错了,你发送的结果不知道fs.readFile在每个文件上运行异步,这意味着文件不读取niether内容被推送到阵列和数组已被发送到客户端 –

+1

我不知道谁低估了这个问题,如果这个问题无效,那么应该在投票时进行评论。所有的问题都不是愚蠢的,如果有人对新的异步式样式他/她会做这样的编码。 –

+0

我虽然我的问题是我使用异步方法,但我试图使用他们的同步对应('readdirSync','readFileSync'),仍然没有得到预期的结果。 – DCruz22

回答

5
一个目录下的所有文件的

阅读内容并将结果发送给客户端,如:

选择1使用npm install async

var fs = require('fs'), 
    async = require('async'); 

var dirPath = 'path_to_directory/'; //provice here your path to dir 

fs.readdir(dirPath, function (err, filesPath) { 
    if (err) throw err; 
    filesPath = filesPath.map(function(filePath){ //generating paths to file 
     return dirPath + filePath; 
    }); 
    async.map(filesPath, function(filePath, cb){ //reading files or dir 
     fs.readFile(filePath, 'utf8', cb); 
    }, function(err, results) { 
     console.log(results); //this is state when all files are completely read 
     res.send(results); //sending all data to client 
    }); 
}); 

选择2使用npm install read-multiple-files

var fs = require('fs'), 
    readMultipleFiles = require('read-multiple-files'); 

fs.readdir(dirPath, function (err, filesPath) { 
    if (err) throw err; 
    filesPath = filesPath.map(function (filePath) { 
     return dirPath + filePath; 
    }); 
    readMultipleFiles(filesPath, 'utf8', function (err, results) { 
     if (err) 
      throw err; 
     console.log(results); //all files read content here 
    }); 
}); 

对于完整的工作解决方案得到这个Github Repo并运行read_dir_files.js

快乐帮助!

+1

'npm install async'后;) – MattMS

+0

它的工作就像一个魅力,谢谢!我只有一个疑问,'async.map()'函数中'cb'参数的功能是什么? – DCruz22

+1

cb是在某些工作完成时应该调用的回调函数,例如文件读取在这种情况下是完整的,因为您必须了解异步性质:) –