问题
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.
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.
回答1:
Read content of all files inside a directory and send results to client, as:
choice 1 using 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
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
Happy Helping!
来源:https://stackoverflow.com/questions/35823727/returning-the-content-of-multiple-files-in-node-js