简体   繁体   English

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

[英]Returning the content of multiple files in node.js

Im using the fs module of node.js to read all the files of a directory and return their content, but the array i use to store the content is always empty.我使用 node.js 的fs模块读取目录的所有文件并返回它们的内容,但我用来存储内容的数组始终为空。

server-side:服务器端:

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 function:阿贾克斯功能:

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

Thanks in advance.提前致谢。

Read content of all files inside a directory and send results to client, as:读取目录内所有文件的内容并将结果发送到客户端,如下所示:

choice 1 using npm install async选择 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
    });
});

choice 2 using npm install read-multiple-files选择 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
    });
});

For complete working solution get this Github Repo and run read_dir_files.js要获得完整的工作解决方案,请获取此Github Repo并运行read_dir_files.js

Happy Helping!乐于助人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM