【问题标题】:the json is override when i use fs.writefilesync当我使用 fs.writefilesync 时,json 被覆盖
【发布时间】:2021-10-17 17:39:07
【问题描述】:

我想在我的儿子文件中添加一些东西,但是当我尝试添加它时,只需覆盖我的儿子文件,有人可以帮助我吗

const fs = require('fs')
const chalk = require('chalk')

const getNotes = function(){
    return 'Your notes....'
}
// add note function 
const addNote = function (title, body) {
    const notes = loadNotes()
    const duplicateNotes = notes.filter(function (note) {
        return note.title === title
    })

    if (duplicateNotes.length === 0) {
        notes.push({
            title: title,
            body: body
        })
        saveNotes(notes)
        console.log(chalk.green.inverse('New note added!'))
    } else {
        console.log(chalk.red.inverse('Note title taken!'))
    }
}
const saveNotes = function(notes){
    const dataJSON = JSON.stringify(notes)
    fs.writeFileSync('notes.json', dataJSON)
}

const loadNotes = function(){
    try{
        const dataBuffer = fs.readFileSync(notes.json)
        const dataJSON = dataBuffer.toString();
        return JSON.parse(dataJSON)
    }catch (e){
        return []
    }
} 



module.exports = {
    getNotes: getNotes,
    addNote: addNote,
}

当我运行 node app.js 添加 --title="list" --body="apple" 然后我添加另一个不同的标题和正文它只是覆盖 --title="list" --body="苹果为什么会这样?

【问题讨论】:

  • 看起来你正在阅读有错误,所以它返回 catch 块 ([])。检查一次

标签: javascript node.js


【解决方案1】:

看来您只是忘记了引号:

const dataBuffer = fs.readFileSync(notes.json)

应该是

const dataBuffer = fs.readFileSync('notes.json')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2012-10-18
    相关资源
    最近更新 更多