返回node.js中多个文件的内容 [英] Returning the content of multiple files in node.js

查看:184
本文介绍了返回node.js中多个文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

服务器端:

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

提前致谢。

推荐答案

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

Read content of all files inside a directory and send results to client, as:

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

For complete working solution get this Github Repo and run read_dir_files.js

快乐帮助!

这篇关于返回node.js中多个文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆