Reputation: 15
I couldn't get contents of files from a folder using Nodejs
I am getting contents of one file using read function but not all files at once.
Upvotes: 0
Views: 979
Reputation: 11
You did a good job. I just want to share my idea.
const lib = {};
lib.base = "/Assignment1/" + "../data/users/";
lib.read = function(dir, file, callback) {
fs.readFile(lib.base + dir + '/' + file + '.json', 'utf-8', function(
err,
data
) {
if (!err && data) {
const parsedData = helpers.parseJsonToObject(data);
callback(false, parsedData);
} else {
callback(err, data);
}
});
};
lib.list = function(dir, callback) {
fs.readdir(lib.base + dir + '/', function(err, data) {
if (!err && data && data.length > 0) {
let trimmedFileName = [];
data.forEach(fileName => {
trimmedFileName.push(fileName.replace('.json', ''));
});
callback(false, trimmedFileName);
} else {
callback(err, data);
}
});
};
Upvotes: 0
Reputation: 15
I got the answer. Here my solution.
function uAll() {
var absPath = __dirname + "/Assignment1/" + "../data/users/";
console.log(absPath);
fs.readdir(absPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
// console.log(file);
var phone = file.split(".");
fops.read('users', phone[0], function (err, newObj) {
if (!err && newObj) { // Read is successful
console.log("Read User: ", newObj);
}
else { // Error in reading
console.log("User not found");
}
});
});
});
}
Upvotes: 0
Reputation: 392
I hope this is correct.
const testFolder = './tests/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
fs.readFile(file, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
});
})
Upvotes: 1