gpt4 book ai didi

node.js - TypeError : notes.推送不是一个函数

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:40 25 4
gpt4 key购买 nike

我正在运行一段简单的代码,如下所示。

基本上我想读取“notes-data.json”中已有的数据,然后将其附加。

node notes.js
console.log('Starting notes.js');

const fs = require('fs');

var addNote = (title, body) => {
var notesString = fs.readFileSync('playground/notes-data.json');
var notes;
notes = JSON.parse(notesString);
var note = {
title,
body
};
notes.push(note);
fs.writeFileSync('playground/notes-data.json', JSON.stringify(note));

};

addNote("Hi", "There");

module.exports = {
addNote: addNote
};

预期:当我运行此程序时,它必须添加“Hi There”。

实际:出现以下错误。

(base) prakashp:newproject2 prakashp$ node notes.js 
Starting notes.js
/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13
notes.push(note);
^

TypeError: notes.push is not a function
at addNote (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13:11)
at Object.<anonymous> (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:18:1)
at Module._compile (internal/modules/cjs/loader.js:721:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
at executeUserCode (internal/bootstrap/node.js:499:15)
at startMainThreadExecution (internal/bootstrap/node.js:436:3)

如果我评论以下行,我不会收到任何错误。

notes = JSON.parse(notesString);

请帮忙。

最佳答案

你的 json 文件应该有一个数组。这是您尝试在 repl 站点上运行的工作代码。在 JSON 解析之后,您的变量需要是一个数组,以便您可以对其使用 push 方法。

我还发现了一个错误,您不应该将 note 保存到 json 文件中,而应该保存 notes。因为您将再次将对象覆盖到文件中,并且将导致应用程序再次崩溃。使用下面的行。

fs.writeFileSync('playground/notes-data.json', JSON.stringify(notes));

Sample Code

关于node.js - TypeError : notes.推送不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56345640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com