fs.readFileSync ReferenceError: fileContents is not defined

fs.readFileSync ReferenceError: fileContents is not defined

我正在尝试从目录中递归读取文件并尝试执行以下代码。

readDirFiles.list('/dir/subDir/', 'utf8', function (err, filenames) {
      if (err) return console.dir(err);
      //filenames haslist of all files and dirs in '/dir/subDir/'

      if(filenames){
        filenames.forEach(function(filename) {
          //filename is full path of file and array also contains sub directory paths

          try {
            console.log('Opening file '+  filename);
            fileContents = fs.readFileSync(filename, 'utf8');
            console.log(md5(fileContents));
          } catch (err) {
            console.log(err);
          }

        }, this);
      }
    });

filenames 我有所有文件和目录的列表,我想从中只读取文件并跳过目录。当我尝试使用 fs.readFileSync(filename, 'utf8') 读取文件时,它给了我两个错误 1. { [Error: EISDIR: illegal operation on a directory, read] errno: -21, code: 'EISDIR', syscall: 'read' } 这个没问题,因为它正在尝试读取目录而不是文件。 2.[ReferenceError: fileContents is not defined] 不知道为什么会出现此错误,因为我正在传递具有正确扩展名的正确文件路径。

  1. fs.readFileSync() 需要文件的完整路径,而不仅仅是名称。 list 返回的 filenames 只是文件名列表,而不是完整路径。
  2. fileContents 在您的示例中未定义为错误所指出的。
  3. 要检查filename是否是文件,需要先使用fs.stat().

    const fs = require('fs');
    const path = require('path');
    
    const dir = '/dir/subDir/';
    
    fs.readdir(dir, function (err, filenames) {
        if (err) {
            return console.dir(err);
        }
    
        // `filenames` haslist of all file names only.
        Promise.all(filenames.map(filename => new Promise((resolve, reject) => {
            const filePath = path.join(dir, filename);
    
            console.log('Opening file '+  filePath);
    
            fs.stat(filePath, (err, stats) => {
                if (err) {
                    return reject(err);
                }
    
                if (stats.isFile()) {
                    const fileContents = fs.readFileSync(filePath, 'utf8');
    
                    console.log(md5(fileContents));
                }
    
                resolve();
            });
        })));
    });
    

在读取文件之前,您应该检查路径是目录还是文件路径。

使用fs.statSync(path).isDirectory()判断是否为目录,忽略

您的脚本可能在顶部有 'use strict',并且由于您没有正确声明 fileContents,所以您收到了引用错误。

要修复,请使用正确的变量声明:

let fileContents = fs.readFileSync(filename, 'utf8');

由于目录不是文件,因此读取失败,您的 fileContents 变量未定义,md5 失败 [ReferenceError: fileContents is not defined]。您应该使用 fs.statSync(path).isDirectory()

使用上述建议的检查