返回node.js中多个文件的内容

我使用node.js的fs模块来读取一个目录的所有文件并返回它们的内容,但是我用来存储内容的数组总是空的。

服务器端:

 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'); }); 

ajaxfunction:

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

提前致谢。

阅读目录内所有文件的内容并将结果发送给客户端,如下所示:

select1使用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 }); }); 

select2使用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 }); }); 

要获得完整的工作解决scheme,请获取此Github Repo并运行read_dir_files.js

快乐帮助!