node.js - 类型错误:notes.push 不是函数
问题描述
我正在运行一段简单的代码,如下所示。
基本上我想读取'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
};
预期:当我运行这个程序时,它必须添加“你好”。
实际:收到以下错误。
(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 Parse 之后,您的变量需要是一个数组,以便您可以push
在其上使用方法。
我还发现了另一个错误,而不是保存note
到您的 json 文件中,您应该保存notes
. 因为您将再次将对象覆盖到文件中,并且会导致应用程序再次崩溃。使用下面的行。
fs.writeFileSync('playground/notes-data.json', JSON.stringify(notes));
推荐阅读
- python - scipy 的 euler 和 rotvec 是一回事吗?
- ajax - 在数据表中加入数据(laravel)
- javascript - 可选链接是在 React 中加载 API 的最佳实践吗?还有哪些其他选择?
- javascript - Uncaught TypeError: this.files is undefined by fr.readAsText(this.files[0]) (FileReader)
- google-chrome - 如果 cookie 在跨站点上下文中并且具有严格的同站点属性,浏览器将拒绝它
- javascript - 为什么我的递减时间功能不起作用?
- shell - Bigquery 表 Mk 命令不起作用 - 架构错误
- azure - 使用二头肌部署逻辑应用 - 将 JSON 转换为有效的二头肌
- python - AWS Sagemaker DeepAR 验证错误 不允许附加属性(“训练”出乎意料)
- objective-c - 带函数参数的 __strong 限定符有什么作用,特别是在 case function (const __strong NSString *const paths[])