如何读取1个目录下所有文件的内容

How to read content of all files in 1 directory

所以我尝试这样做,但无法正常工作。 在每个文件中都有这样的随机数“12”,我需要检查所有文件并选择编号最大的一个,然后在变量中获取该文件的文件名。

这是我目前尝试过的方法

function readFiles(dirname, onFileContent, onError) {
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
      onError(err);
      return;
    }
    filenames.forEach(function(filename) {
      fs.readFile(dirname + filename, "utf-8", function(err, content) {
        if (err) {
          onError(err);
          return;
        }
        onFileContent(filename, content);
      });
    });
  });
}

谢谢大家的回复。

/* Returns filename of file containing the largest integer within a specified directory */
const getFileWithLargestInteger = (pathToFolder) => {
  const files = fs.readdirSync(pathToFolder);
  const content = files.map(f => +fs.readFileSync(`${pathToFolder}/${f}`, 'UTF-8'));
  const largestInteger = Math.max(...content);
  const fileWithLargestInteger = files[content.indexOf(largestInteger)];

  return fileWithLargestInteger;
}

如果有两个相同编号的文件怎么办?

const getSecondFileName = (pathToFolder) => {
      const files = fs.readdirSync(pathToFolder);
      const content = files.map(f => +fs.readFileSync(`${pathToFolder}/${f}`, 'UTF-8'));
      const arrayCopy = [...content];
      const secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]
      const secondFileWithLargestInteger = files[content.indexOf(secondLargestNum)];

      return secondFileWithLargestInteger;        
    }