首先,我是node.js和JavaScript的菜鸟。
我正在尝试编写一个使用yargs在本地系统中存储用户注释的程序。
我在处理程序中的直通列车如下-
首先创建一个包含便笺标题及其内容的对象。
我假设文件总是在用户的本地系统中创建的,要么为空,要么有一些注释。
获取文件的内容,如果文件为空,则创建一个包含所有注释数组的对象,并将注释推入该对象。然后,在执行必要的JSON操作后,我将其写入文件。
如果文件中已存在对象,则只需将新注释推入该对象。
这是我的代码
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)
我已经尝试了很多铰链,但无法消除该错误。有人可以帮我吗。任何其他有助于我更好地理解此概念的有用信息/资源,将不胜感激。
关于在节点中使用JSON的任何解释/资源(如JSON.stringify,JSON.parse都会很有帮助。
提前感谢
我通过用一个空数组填充文件来解决。
如@GuyIncognito指出的,当文件为空时,错误弹出。
感谢大家的帮助