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

Returning the content of multiple files in node.js

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

服务器端:

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 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

帮助愉快!