MST

星途 面试题库

面试题:JavaScript在Node中如何批量读取文件内容

请使用JavaScript的Node.js编写代码,实现批量读取指定目录下所有.txt文件的内容,并打印出文件内容。需要处理文件读取过程中的错误。
49.1万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
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');