错误:定义的函数不是函数

时间:2019-09-02 05:39:22

标签: javascript node.js

我正在创建一个应用程序以在Node.js中添加,保存,读取和删除注释,但是我的应用程序无法读取功能。

起初,我没有在驱动程序代码中调用后台代码,当时我遇到了另一个错误。现在,我已经在代码中“需要”文件,它说“ notes.addNotes不是函数”

const notes = require('./notes.js')
const yargs = require('yargs')

yargs.command({
    command: 'add',
    description: 'Adds a new note',
    builder: {

        body: {

            description: 'Inside of the note',
            demandOption: true,
            type: 'string' 
        },
        title: {
            description: 'Note title',
            demandOption: true,
            type: 'string'

        }

    },
    handler: function(argv){

    notes.addNotes(argv.title, argv.body)
    }
})

-------------------------------- Notes.js文件----------- ---------------------

const fs = require('fs')

const getNotes = function() {

}

const loadNotes = function() {

    try{

    const dataBuffer = fs.readFileSync('notes.json')
    const dataJSON = dataBuffer.toString()
    return JSON.parse(dataJSON)

    } catch(error){

            return []

    }


}

const addNotes = function(title,body) {

    const notes = loadNotes()

    notes.push({
        title: title,
        body: body,
    })
    saveNotes(notes)
}

module.exports={
    getNotes: getNotes,
    addNote: addNotes
}

当我在文件中添加任何内容时,我期望会创建一个JSON文件,但是该文件未创建,并且出现错误提示notes.addNotes不是函数

2 个答案:

答案 0 :(得分:1)

在这里,您将addnotes函数设置为“ notes.addNote”

module.exports={
    getNotes: getNotes,
    addNote: addNotes
}

此处您正在调用范围中不存在的“ notes.addNotes”。

notes.addNotes(argv.title, argv.body)

因此,可以在某处添加或删除“ s”。

答案 1 :(得分:0)

尝试以下方法

-------------------------------- Notes.js文件----------- ---------------------

const fs = require('fs')
const notes = {};
const getNotes = function() {

}

 notes.loadNotes = function() {

    try{

    const dataBuffer = fs.readFileSync('notes.json')
    const dataJSON = dataBuffer.toString()
    return JSON.parse(dataJSON)

    } catch(error){

            return []

    }


}

notes.addNotes = function(title,body) {

    const notes = loadNotes()

    notes.push({
        title: title,
        body: body,
    })
    saveNotes(notes)
}

module.exports =  notes; 

像上面的代码一样更新节点文件。
它会解决您的问题。如果是这样,请对答案进行投票。