我正在尝试从目录中递归读取文件并尝试执行以下代码。
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]
不知道为什么会出现此错误,因为我正在传递具有正确扩展名的正确文件路径。
最佳答案
您的脚本可能在顶部有 'use strict'
,并且由于您没有正确声明 fileContents
,您会收到引用错误。
要修复,请使用适当的变量声明:
let fileContents = fs.readFileSync(filename, 'utf8');
关于javascript - fs.readFileSync 引用错误 : fileContents is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920916/