Проблема с обходом файловой системы с использованием Node.js - PullRequest
0 голосов
/ 06 августа 2020

Я все время получаю сообщение об ошибке «Ошибка: ENOENT: нет такого файла или каталога, откройте« t1.txt »», когда я запускаю функцию, начиная с каталога верхнего уровня, показанного ниже. Я думаю, это связано с тем, что 'fs.readFileSyn c ()' пытается прочитать содержимое файла из каталога, отличного от того, в котором объявлена ​​fs, хотя я не совсем уверен.

Изображение структуры каталогов

/* the built-in Node.js 'fs' module is included in our program so we can work with the computer's file system */
const fs = require('fs');

// used to store the file contents of the files encountered 
const fileContents = {};

/* stores the duplicate files as subarrays within the array, where the first element of the subarray is the duplicate file, and the second element is the original */
let duplicateFiles = [];

const traverseFileSystem = function (currentPath) {
  // reads the contents of the current directory and returns them in an array 
  let files = fs.readdirSync(currentPath);
  // for-in loop is used to iterate over contents of directory 
  for (let i in files) {
    let currentFile = currentPath + '/' + files[i];
    // retrieves the stats of the current file and assigns them to a variable
    let stats = fs.statSync(currentFile);
    // it's determined if the 'currentFile' is actually a file
    if (stats.isFile()) {
      /* if the file's contents are in the 'fileContents' object, then a new file has been encountered */
      if(fileContents[fs.readFileSync(files[i])] === undefined) {
        // the file's contents are set as the key, and the file path as the value
        fileContents[fs.readFileSync(files[i])] = currentFile;
      }
      // otherwise, the file's contents already exist in the 'fileContents' object, which means a duplicate file has been found 
      else {
        duplicateFiles.push([fileContents[fs.readFileSync(files[i])], currentFile]);
      }
    }
    /* if the 'file' is actually a directory, traverseFileSystem() is called recursively on that directory */
    else if (stats.isDirectory()) {
      traverseFileSystem(currentFile);
    }
  }
  return duplicateFiles;
};

1 Ответ

1 голос
/ 07 августа 2020

У вас есть fs.readFileSync(files[i]), который должен быть fs.readFileSync(currentFile) в зависимости от вашего кода. Не удалось подтвердить ваш лог c, но это должно решить текущую ошибку.

...