【发布时间】:2020-09-02 04:37:55
【问题描述】:
console.log(`./settings/${mob.serverName}/${mob.channelName}.json`); // ./settings/Mobbot Test Server/mobtimusprime.json
fsp.writeFile(`./settings/${mob.serverName}/newfile.json`, settings); // actually creates the right file, in the right path
console.log(fs.existsSync(`./settings/${mob.serverName}`)); // true
fsp.writeFile(`./settings/${mob.serverName}/${mob.channelName}.json`, settings); // does nothing, doesn't throw an error, just does absolutely nothing.
我不知道发生了什么,我已经检查了多次拼写,但一切似乎应该工作,但没有。
附加信息:
node -v // v14.2.0
窗户 10
顺便说一句:
const fsp = require('fs').promises;
如果这不是很明显。
编辑: 这更像是我正在尝试做的事情(当然,显示问题所需的最少代码)。
const myFunc = async (settings) => {
try {
return await fsp.writeFile(`./settings/${mob.serverName}/${mob.channelName}.json`, settings);
} catch (e) {
console.log(e)
}
}
编辑 2:
更多上下文:
const settingsUpdater = async (settings) => {
try {
return await fsp.writeFile(`./settings/${mob.serverName}/${mob.channelName}.json`, settings);
} catch (e) {
console.log(e)
}
}
const callingFunction = async (...args) {
try {
await settingsUpdater(settings);
const { pieceOfUpdatedSettings } = require(`../settings/${mob.serverName}/${mob.channelName}.json`);
anotherFunction(pieceOfUpdatedSettings);
} catch (e) {
console.log(e)
}
}
【问题讨论】:
-
您能补充更多信息吗?当您说文件系统不想写时,实际上发生了什么?你有错误吗?
-
我没有收到任何错误,代码继续运行,就好像什么都没发生一样,并且文件没有被创建或更新。
-
感谢您更新问题。我无法想象是什么原因造成的。只是 FWIW(与具体问题无关),不需要
return await,从async函数返回的值总是有效的awaited(例如,只需return就足够了)。return awaitused 导致函数的结算需要一个额外的异步滴答,但 ES2019 修复了该问题(对于本机承诺)。还强烈建议不要使用undefined将拒绝转换为解决方案,catch块就是这样做的。 :-) 希望你能找到问题! -
感谢您的提示,所以您是说我不应该有一个 catch 块?
-
我不推荐使用 catch 块和异步函数。如果你想读取一个带有 Promise 的文件,它会是:
const fs = require('fs')和fs.readFile(path).then(res => { processing response... }).catch(err => { processing error... });。您还可以使用回调。希望对您有所帮助。
标签: javascript node.js fs