Node.js 中可以使用 fs
模块来读取文件内容。以下是一个简单的示例代码,展示如何使用 fs
模块读取指定目录下的所有文件类型的内容:
const fs = require('fs');
const path = require('path');
function readFileContents(dirPath) {
fs.readdir(dirPath, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
files.forEach(file => {
const filePath = path.join(dirPath, file);
fs.stat(filePath, (err, stats) => {
if (err) {
console.error('Error getting file stats:', err);
return;
}
if (stats.isFile()) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading file ${filePath}:`, err);
return;
}
console.log(`File: ${filePath}`);
console.log(`Content: ${data}`);
});
} else if (stats.isDirectory()) {
readFileContents(filePath); // Recursively read files in subdirectories
}
});
});
});
}
// Usage example:
readFileContents('./your-directory-path');
fs.readFileSync()
方法,适用于小文件或不需要高并发处理的场景。fs.readFile()
方法,适用于大多数情况,特别是需要处理大量文件或高并发请求的场景。EACCES
错误,表示没有足够的权限读取文件或目录。解决方法是为运行 Node.js 进程的用户授予相应的权限。path.join()
来构建路径。readFileContents
函数,可以遍历并读取指定目录及其所有子目录中的文件。通过这种方式,你可以有效地读取指定目录下的所有文件类型的内容,并处理可能遇到的各种问题。
没有搜到相关的文章