【问题标题】:How to read content of all files in 1 directory如何读取 1 个目录中所有文件的内容
【发布时间】:2020-02-04 06:47:37
【问题描述】:

所以我试着去做,但我无法让它工作。 每个文件中都有像“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);
      });
    });
  });
}

谢谢大家的回复。

【问题讨论】:

  • 欢迎来到 Stack Overflow!请在提出问题时尽可能具体,并至少提供部分代码。你是什​​么意思每个文件都有一个数字?怎么样?
  • 在每个文件中都是随机数,我需要获取编号最大的文件。
  • 文件中的数字是如何存储的?你试过什么?
  • function readFiles(dirname, onFileContent, onError) { fs.readdir(dirname, function(err, filenames) { if (err) { onError(err); return; } filenames.forEach(function(文件名) { fs.readFile(dirname + filename, 'utf-8', function(err, content) { if (err) { onError(err); return; } onFileContent(filename, content); }); }); }); }
  • @NotBad 编辑您的答案并在此处添加适当的信息/代码,不要将其粘贴到 cmets 中。

标签: node.js fs


【解决方案1】:
/* 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;
}

【讨论】:

  • 当我尝试将它记录到控制台时,我得到 undefined console.log(fileWithLargestInteger);
  • 您不能访问超出其范围的变量。你需要做console.log(getFileWithLargestInteger('<Path to folder here>'));
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2013-11-27
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多