【发布时间】:2021-12-03 01:41:03
【问题描述】:
我可能遗漏了一些明显的东西,但我花了几天时间寻找这个问题的解决方案,但没有找到任何解决方案。
我有一个函数,它接收一个对象,把它变成一个字符串,然后使用节点文件系统来保存它。它应该在文件返回之前等待文件完成写入,但是,无论出于何种原因,它都没有。
相反,函数开始写入文件并调用.then (),并在文件写入之前继续。该文件确实完成了写入,但它只发生在 promise 已经解决之后,因此,在函数已经继续之后。
我使用的是 node.js,它是原生的 fs.promises api,这是许多类似问题所暗示的(尽管其中许多问题来自 fs.promises 仍处于试验阶段)
代码:
const fs = require(`fs`);
const fsPromises = fs.promises;
const path = require (`path`);
var server = `test`;
const settings = {
"name": "srvr.name",
"serverId": "srvr.id",
"ownerId": "srvr.ownerId",
"prefix": "!",
"roles":
{
"bot":
{
"id": "srvr.me.roles.highest.id",
"name": "srvr.me.roles.highest.name"
}
}
};
saveSettings (server, settings);
功能:
async function saveSettings (server, settings) {
const newSettings = await JSON.stringify (settings, null, `\t`);
await fsPromises.writeFile (path.join (__dirname, `${server}.json`), newSettings)
.then (console.log (`File Saved`));
await console.log (fs.readFileSync (path.join (__dirname, `${server}.json`)));
return console.log (`Settings Saved`);
}
预期结果:
File Saved
{
"name": "srvr.name",
"serverId": "srvr.id",
"ownerId": "srvr.ownerId",
"prefix": "!",
"roles":
{
"bot":
{
"id": "srvr.me.roles.highest.id",
"name": "srvr.me.roles.highest.name"
}
}
}
Settings Saved
实际结果:
File Saved
<Buffer 7b 0a 09 22 6e 61 6d 65 22 3a 20 22 73 72 76 72 2e 6e 61 6d 65 22 2c 0a 09 22 73 65 72 76 65 72 49 64 22 3a 20 22 73 72 76 72 2e 69 64 22 2c 0a 09 22 ... 150 more bytes>
Settings Saved
如您所见,当函数尝试读取文件时,该文件仍在写入中。
据我了解,fs.promises.writeFile 返回一个承诺,该承诺将在文件完成写入后解决,但似乎并没有这样做。
我开始使用 fs.writeFile,但发现它没有返回承诺,因此 await 无法使用它。 我也尝试过 fs.writeFileSync,以防万一,但正如预期的那样,它没有。
我不知道对象是否太大,因此文件需要很长时间才能写入,但据我所知,这应该不是问题,因为承诺在文件完成之前不会解决已经写好了,不管它需要多长时间。
我知道我可能在这里遗漏了一些非常明显的东西,无论是我遗漏了 writeFile 的工作方式,还是完全使用了错误的功能,但我不知道是什么。
如果有用,此功能可用于使用 Discord.js 的 Discord 机器人
提前致谢
【问题讨论】:
-
As you can see, the file is still being written when the function attempts to read it.看看哪里? -
添加编码到 readFileSync
readFileSync(..., 'utf8')
标签: javascript node.js fs