Javascript 返回node.js中多个文件的内容
我使用node.js的Javascript 返回node.js中多个文件的内容,javascript,ajax,node.js,fs,Javascript,Ajax,Node.js,Fs,我使用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(functi
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');
});
ajax功能:
$.ajax({
type: 'GET',
url: '/getCars',
dataType: 'JSON',
contentType: 'application/json'
}).done(function( response ) {
console.log(response);
});
提前感谢。读取目录中所有文件的内容并将结果发送给客户端,如下所示: 选择1使用
npm安装异步
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安装读取多个文件
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
});
});
要获得完整的工作解决方案,请获取并运行read\u dir\u files.js
乐于助人 您这样做是错误的,您发送结果时不知道fs.readFile在每个文件上运行异步,这意味着文件未被读取,其他内容被推送到数组,数组已发送到客户端。我不知道是谁否决了此问题,如果此问题无效,则应在否决投票时进行评论。所有的问题都不是愚蠢的,如果有人不熟悉异步风格的范例,他/她会做这样的编码。我认为我的问题是我在使用异步方法,但我尝试使用它们的同步对应(
readdirSync
,readFileSync
)但仍然没有得到预期的结果。不要做同步编码,充分利用异步,看看这里的模拟版本,它工作得很好,它真的工作得很好,我如何了解node.js上异步函数的更多信息?。顺便说一句,谢谢你的帮助!在npm之后安装异步;)它很有魅力,谢谢!。我只是有一个疑问,async.map()
函数上的cb
参数的函数是什么?cb是一个回调,应该在完成某些工作时调用,比如在本例中文件读取完成,因为您必须了解异步性质:)我将进一步深入到异步性质。谢谢你的帮助!