I have the problem that the file does not yet exist before it is read out. As a result, I keep getting the error message no such File
.
To the best of my knowledge fs.writeFileSync(); should solve that ...?
function in modul:
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;
},
Function that calls the function:
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);
}
}
Your setup function needs to be async Make the following changes to your function declaration:
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;
}
Now to call that function:
dashboard.setup(server, message).then((msg) => {
// Use the returned value of msg
})
This should work, but I recommend using fs.readFile instead of fs.readFileSync since it will hold up the single thread loop while I/O is being performed and other process cannot continue until it's done.