You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中fs.readFileSync回调导致数组push失效问题求助

问题原因与解决方案

问题核心原因

  • 你误用了fs.readFileSync:这是同步读取文件的方法,它不接受回调函数作为参数,你写的回调代码永远不会被执行,自然无法把值push进names数组。
  • 就算回调能执行,同步的res.json(names)也会在异步回调之前执行,但这里的核心问题是readFileSync的用法错误。

方案一:修正同步读取的写法

直接使用fs.readFileSync的返回值,不需要回调:

app.get("/overview", (req,res)=>{
    const email = "jack.pro.official@gmail.com"

    const getFiles = (directoryPath) => {
        const files = new Array();
        const directories = fs.readdirSync(directoryPath);
        
        for (const directory of directories) {
            const fullPath = path.join(directoryPath, directory);
            if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
                const subFiles = getFiles(fullPath);
                files.push(...subFiles);
            } else {
                files.push(fullPath);
            }
        }

        return files;
    };

    const files = getFiles('./ToDoLists/jack.pro.official@gmail.com/');
    const names = new Array();

    files.forEach((fileName) => {
        // 同步读取直接获取返回值,无需回调
        const data = fs.readFileSync(fileName, 'utf8');
        const parsedData = JSON.parse(data);
        const name = parsedData.toDoListName;
        names.push(name);
    });
    
    return res.json(names);
})

方案二:改用异步读取(推荐,避免阻塞事件循环)

如果文件数量较多,同步读取会阻塞Node.js事件循环,推荐用fs.promises.readFile结合Promise.all处理:

app.get("/overview", async (req,res)=>{ // 新增async标记
    const email = "jack.pro.official@gmail.com"

    const getFiles = (directoryPath) => {
        const files = new Array();
        const directories = fs.readdirSync(directoryPath);
        
        for (const directory of directories) {
            const fullPath = path.join(directoryPath, directory);
            if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
                const subFiles = getFiles(fullPath);
                files.push(...subFiles);
            } else {
                files.push(fullPath);
            }
        }

        return files;
    };

    const files = getFiles('./ToDoLists/jack.pro.official@gmail.com/');
    
    // 把每个文件读取操作包装为Promise
    const namePromises = files.map(async (fileName) => {
        const data = await fs.promises.readFile(fileName, 'utf8');
        const parsedData = JSON.parse(data);
        return parsedData.toDoListName;
    });

    // 等待所有读取操作完成,获取完整name数组
    const names = await Promise.all(namePromises);
    
    return res.json(names);
})

内容的提问来源于stack exchange,提问作者Jack Pro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:32:04