const fs = require('fs');
const path = require('path');
function readTxtFilesInDir(dirPath) {
try {
const files = fs.readdirSync(dirPath);
files.forEach(file => {
if (path.extname(file) === '.txt') {
const filePath = path.join(dirPath, file);
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(`读取文件 ${filePath} 出错:`, err);
return;
}
console.log(`文件 ${filePath} 的内容:\n`, data);
});
}
});
} catch (err) {
console.error('读取目录出错:', err);
}
}
// 调用函数,传入指定目录路径
readTxtFilesInDir('/your/directory/path');