【问题标题】:JSON file can't be modifiedJSON 文件无法修改
【发布时间】:2019-12-12 16:13:12
【问题描述】:

我目前正在创建一个使用可以存储为 JSON 格式的变量的 Web。我的计划是每次连接到某个路由时修改 JSON 的值。问题是它不会写。

我曾尝试使用 fs.writeFile 和 fs.writeFileSync 但它们似乎都不起作用。

// Code I Have tried
const kwitansi = require('./no_kwitansi.json')

app.get('', async (req, res) => {
    kwitansi.no_kwitansi += await 1
    await fs.writeFile('../no_kwitansi.json', JSON.stringify(kwitansi, null, 2), function (e) {
        if (e) {
            throw new Error
        } else {
            console.log('Wrote to file')
        }
    })
    await console.log(kwitansi)
    await res.send(kwitansi)
})

// An Example of my JSON File
{
    "no_kwitansi":4
}

【问题讨论】:

    标签: node.js json fs


    【解决方案1】:

    您正在尝试写入您没有权限的地方。请注意,您打开了./no_kwitansi.json,但您正在尝试写入../no_kwitansi.json(返回一个目录)。如果您确定可以替换原始文件,请删除写入行中多余的.

    如果错误仍然存​​在,您还需要确保您具有写入文件的适当权限。如果你使用*nix或者mac,可以查看this link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 2012-02-19
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      相关资源
      最近更新 更多