首页 > 解决方案 > 无法创建 notes.json 文件

问题描述

这是app.js代码:

const chalk = require('chalk');
const validator = require('validator');
const yargs = require('yargs');
const notes = require('./notes.js');
yargs.version('1.1.0');
yargs.command[{
    command: 'add',
    describe: 'Add a New Note',
    builder: {
        title: {
            describe: 'Note Title',
            demandOption: true,
            type: 'string'
        },
        body: {
            describe: 'the body of the note',
            demandOption: true,
            type: 'string'
        }
    },
    handler: function (argv) {
        notes.addNote(argv.title, argv.body)
    }
}]
yargs.parse();

文件notes.js

const fs = require('fs');

const getNotes = function() {
}
const addNote = function(title, body) {
    const notes = loadNotes();
    notes.push({
        title: title,
        body: body
    });
    savedNotes(notes);
}
const savedNotes = function(notes) {
    const dataJson = JSON.stringify(notes);
    fs.writeFileSync('notes.json',dataJson);
}
const loadNotes = function() {
    try {
        const dataBuffer = fs.readFileSync('notes.json');
        const dataJson = dataBuffer.toString();
        return JSON.parse(dataJson);
    } catch(e) {
       return {};
    }
}
module.exports = {
    getNotes: getNotes,
    addNote: addNote
}

但是,我仍然无法notes.json通过 .push 创建文件fs.writeFileSync(),并且如果在显示错误后放置一个圆括号yargs.command,说明 .push 不是我从notes.js文件中使用的函数

标签: javascriptnode.js

解决方案


推荐阅读