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

时间:2016-03-06 06:02:48

标签: 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(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 个答案:

答案 0 :(得分: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

快乐帮助!