为什么我在使用 nodeJS 和 yargs 时不断收到错误提示 JSON 输入意外结束

Why do I keep getting an error saying I have unexpected end of JSON input while using nodeJS and yargs

首先,我是node.js和JavaScript的菜鸟。

我正在尝试编写一个程序,使用 yargs 在本地系统中存储用户的笔记。

我在handler中的through流程如下-

  1. 首先创建一个包含笔记标题及其内容的 object。

  2. 我假设文件总是在用户的本地系统中创建,并且要么是空的,要么有一些注释。

  3. 获取文件内容,如果为空,则创建一个object,其中包含所有笔记的数组,并将笔记推送到其中。然后我在进行必要的 JSON 操作后将其写入文件。

  4. 如果文件中已经存在 object,我只需将新注释推送给它。

这是我的代码

const yargs = require("yargs")
const fs = require("fs")


yargs.command({

    command: "add",

    describe: "Add a note",

    builder: {
        title: {
            describe: "Title of the note to add",
            demandOption: true,
            type: "string"
        },
        note: {
            describe: "Contents of the note to add",
            demandOption: true,
            type: "string"
        }
    },

    handler: function() {

        let fullNote = {
            title: yargs.argv.title,
            note: yargs.argv.note
        }

        let fileContents = JSON.parse(fs.readFileSync("notes.json").toString())

        if(fileContents === undefined || fileContents === null){
            let newArrayJSON = {
                notes: []
            }

            newArrayJSON.notes[0] = JSON.stringify(fullNote)

            fs.writeFileSync("notes.json", newArrayJSON)

        } else {
            fileContents.notes.push(JSON.stringify(fullNote))

            fs.writeFileSync("notes.json", newArrayJSON)
        }

    }
})

yargs.parse()

这是我收到的错误消息

PS D:\Documents\Projects\Node\Node-NotesApp> node app.js add --title="To Buy" --note="Eggs"
D:\Documents\Projects\Node\Node-NotesApp\node_modules\yargs\yargs.js:1242
      else throw err
           ^

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Object.handler (D:\Documents\Projects\Node\Node-NotesApp\app.js:34:33)
    at Object.runCommand (D:\Documents\Projects\Node\Node-NotesApp\node_modules\yargs\lib\command.js:240:40)
    at Object.parseArgs [as _parseArgs] (D:\Documents\Projects\Node\Node-NotesApp\node_modules\yargs\yargs.js:1154:41)
    at Object.parse (D:\Documents\Projects\Node\Node-NotesApp\node_modules\yargs\yargs.js:599:25)
    at Object.<anonymous> (D:\Documents\Projects\Node\Node-NotesApp\app.js:54:7)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)

我已经尝试了很多次,但无法摆脱那个错误。 有人可以帮助我吗?任何其他有助于 information/resources 帮助我更好地理解这个概念的人都将不胜感激。

关于在节点中使用 JSON 的任何 explanations/resources(如 JSON.stringify、JSON.parse)都会非常有帮助。

提前致谢

我通过用空数组填充文件解决了这个问题。

正如@GuyIncognito 指出的那样,当文件为空时弹出错误。

感谢大家的帮助