node.js - TypeError: notesExist.push 不是函数?
问题描述
我只是 nodeJs 的新手,我需要你的帮助
我的utile.js 文件:
const fs = require('fs');
const addNotes = function(name,age,birthday){
const notesExist = loadNotes()
notesExist.push({
name: name,
age: age,
birthday:birthday
})
}
const loadNotes = function (){
try{
binaryVersion = fs.readFileSync('./JsonFile/data.json');
stringVersion = binaryVersion.toString();
dataParsed = JSON.parse(stringVersion);
return dataParsed;
}
catch(err){
return [];
}
}
module.exports = {
addNotes: addNotes,
loadNotes: loadNotes
}
我的 intro.js 文件
yargs = require('yargs');
const utile = require('./utile.js');
yargs.command({
command: 'add',
describe: 'Adding new record',
builder:{
name:{
describe:'note name',
demandOption:true, // title option to be requires in the command line
type:'string' //requie a string as title value
},
age:{
describe:'note age',
demandOption:true,
type:'string' //require astring as body value
},
birthday:{
describe:'note birthday',
demandOption:true,
type:'string' //require astring as body value
},
},
handler: function(argv){
// console.log(chalk.green(chalk.red(argv.title)))
/* console.log(chalk.green(chalk.green(argv.body))) */
utile.addNotes(argv.name,argv.age,argv.birthday);
}
});
我的 data.json 文件:
{"name":"Hannani","age":25,"birthday":1995}
但是当我通过以下方式运行 intro.js 文件时:node intro.js add --name="booktitle" --age="dsds" --birthday="1995"
我得到了很好的错误 [我花了 3 个小时,但我没有找到任何解决该错误的方法]
错误:
/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1195
else throw err
^
TypeError: notesExist.push is not a function
at Object.addNotes (/home/simo/Documents/nodeJs/utile.js:34:20)
at Object.handler (/home/simo/Documents/nodeJs/intro.js:56:19)
at Object.runCommand (/home/simo/Documents/nodeJs/node_modules/yargs/lib/command.js:240:40)
at Object.parseArgs [as _parseArgs] (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1107:41)
at Object.parse (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:566:25)
at Object.<anonymous> (/home/simo/Documents/nodeJs/intro.js:86:7)
at Module._compile (internal/modules/cjs/loader.js:1151:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
ps:我没有更改我的 yargs.js 文件中的任何内容。请问我做错了什么?提前致谢 !
解决方案
必须data.json
是数组格式才能推送。像这样的东西
[{"name":"Hannani","age":25,"birthday":1995}]
此外,由于它是一个普通的 json 文件,您可以简单地要求它而不是使用fs
它来读取它。
const data = require('./JsonFile/data.json')
希望这可以帮助。
推荐阅读
- linux - 构建 libwebrtc
- android - Android/Firebase - TextView 未显示在 ListView 中
- java - 使用 touchDragged 方法后如何找出演员在 libgdx 中的新位置?
- laravel - FTP 一个 Laravel 项目
- angular - 在 mat table 中显示动态列
- mysql - 如何用一个查询搜索多个单词?
- java - 如何从 Spring Boot Client 到 GlassFish Server 进行远程 JNDI 查找?
- swift - 致命错误:在使用 IB Outlet 隐式展开可选值时意外发现 nil
- python - 检测语言并与单词列表进行比较
- java - Apache FOP 无法通过 fatJar 中的 URI 找到外部图像