简体   繁体   中英

How to display contents of all files from a folder in console using node.js or express

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.

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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