首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使函数同步node.js

使函数同步node.js
EN

Stack Overflow用户
提问于 2021-08-29 14:21:53
回答 1查看 46关注 0票数 1

我有一个问题,那就是文件在被读出之前还不存在。结果,我一直收到错误消息no such File。据我所知,fs.writeFileSync();应该解决这个问题...?

模块中的函数:

代码语言:javascript
运行
复制
setup: function(server, RAM, client, message) {
    const dc = require("../libs/dcTools.js");
    const db = require('../libs/dbTools.js');
    const fs = require('fs');
    const channel = dc.getChannel(message, server.dashboard.channel);
    const dashboard = this.create(server, RAM, client);
    channel.send(dashboard).then(msg => {
      //that is the line ↓
fs.writeFileSync(`./RAM/${server.id}/dsbdmsgid.txt`, msg.id);
      console.log('done');
    });
//and this line produces the error ↓
    const msg = fs.readFileSync(`./RAM/${server.id}/dsbdmsgid.txt`, 'utf8');
    return msg;
  },

调用该函数的函数:

代码语言:javascript
运行
复制
execute(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;
//function ↓
    server.dashboard.msg = 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);
    }
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-29 15:51:11

您的setup函数需要是异步的,请对函数声明进行以下更改:

代码语言:javascript
运行
复制
setup: async function(server, RAM, client, message) {
    const dc = require("../libs/dcTools.js");
    const db = require('../libs/dbTools.js');
    const fs = require('fs');
    const channel = dc.getChannel(message, server.dashboard.channel);
    const dashboard = this.create(server, RAM, client);
    channel.send(dashboard).then(msg => {
      //that is the line ↓
    fs.writeFileSync(`./RAM/${server.id}/dsbdmsgid.txt`, msg.id);
      console.log('done');
    });
     //and this line produces the error ↓
    const msg = fs.readFileSync(`./RAM/${server.id}/dsbdmsgid.txt`, 'utf8');
    return msg;
  }

现在调用该函数:

代码语言:javascript
运行
复制
dashboard.setup(server, message).then((msg) => {
    // Use the returned value of msg
})

这应该是可行的,但我建议使用fs.readFile而不是fs.readFileSync,因为它会在执行I/O时阻塞单线程循环,并且其他进程在完成之前无法继续。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68973823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档