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

Node.js使用fs.writeFileSync后读文件仍报no such file错误如何解决

问题根因
  • 核心是异步执行顺序问题:channel.send() 是异步方法,返回 Promise 对象,你写在 .then() 回调里的 fs.writeFileSync() 会等到 Discord 消息发送成功后才会执行;但回调外的 fs.readFileSync() 是同步代码,会在调用 channel.send() 之后立刻执行,此时 .then() 里的写文件逻辑还没触发,目标文件自然不存在,就会抛出 no such file 错误。
  • 额外潜在问题:你没有提前判断 ./RAM/${server.id}/ 这个目录是否存在,如果目录本身不存在,就算执行到写文件逻辑,fs.writeFileSync() 也会抛同样的不存在错误。
修复方案

第一步:调整异步执行顺序,改写为 async/await 逻辑

修改setup函数为异步函数,等待消息发送完成再执行读写逻辑,同时增加目录存在性校验:

// 给setup函数加async标记
setup: async function(server, RAM, client, message) {
    const dc = require("../libs/dcTools.js");
    const db = require('../libs/dbTools.js');
    const fs = require('fs');
    const path = require('path');
    // 提前拼接目录路径,判断是否存在,不存在就创建
    const dirPath = path.join('./RAM', server.id);
    if (!fs.existsSync(dirPath)) {
        // recursive=true支持一次性创建多级缺失目录
        fs.mkdirSync(dirPath, { recursive: true });
    }
    const channel = dc.getChannel(message, server.dashboard.channel);
    const dashboard = this.create(server, RAM, client);
    // 等待消息发送完成,无需写.then回调
    const msg = await channel.send(dashboard);
    const filePath = path.join(dirPath, 'dsbdmsgid.txt');
    fs.writeFileSync(filePath, msg.id);
    console.log('done');
    const msgId = fs.readFileSync(filePath, 'utf8');
    return msgId;
}

第二步:修改调用处逻辑,等待异步setup执行完成

因为setup改为了异步函数,返回Promise,调用位置也需要增加await等待执行完成:

// 给execute函数加async标记
execute: async function(server, message) {
    const fs = require('fs');
    const db = require('../../libs/dbTools.js');
    const dashboard = require('../../modules/dashboard.js');
    if (args[0] == "setup") {
        server.dashboard.channel = message.channel.id;
        // 加await等待setup执行完成
        server.dashboard.msg = await dashboard.setup(server, message);
        console.log('ready');
        server.dashboard.mod = true;
        db.updateServer(server);
    } else if (args[0] == "off") {
        server.dashboard.mod = false;
        db.updateServer(server);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:39:03