调用一个函数到console.log时,NodeJS对象是未定义的(`$ {note.title}`)

时间:2018-04-24 22:00:54

标签: javascript node.js

我只想查看我的notes.j,当我打电话时返回notes.logNote(注释):node app.js add --title=" " ,如果声明--title=" ",则不会在notes-data.json中写入。

这是我的app.js

const fs = require('fs');
const os = require('os');
const _ = require('lodash');
const yargs = require('yargs');
const notes = require('./notes.js')
const argv = yargs.argv;

var command = argv._[0];
console.log(' Your Command: ', command);
console.log(' Your processes is: ',process.argv);
console.log(' Your Yargs is: ', argv);

if (command === 'add') {
    var note = notes.addNote(argv.title, argv.body);
    if (note) {
        console.log(" You write the new object in notes");
        notes.logNote(note);
    } else {
        console.log(" You write an exist objects in node");
        console.log(' -- which is');
        notes.logNote(note);
        // here I can't call note.title = undifiend same with note.body = undifined
        // I want to log the title if was exists
         // console.log(` Title: ${note.title}`);
         // console.log(` body: ${note.body}`);
    } else {
      console.log(' Your command not in my list command that i made');
};

我从notes.js中调用了一些函数

const fs = require('fs');
var fetchNotes = () => {
  try {
      var noteString = fs.readFileSync('notes-data.json');
      return JSON.parse(noteString);
  } catch (e) {
      return [];
  }
};    

var saveNotes = (notes) => {
    fs.writeFileSync('notes-data.json', JSON.stringify(notes));
}; 

var logNote = (note) => {
console.log(' -- which is');
console.log(` Title: ${note.title}`);
console.log(` body: ${note.body}`);
};        

var addNote = (title, body) => {
  var notes = fetchNotes();
  var note = {
      title,
      body
  };       
  var duplicatesNotes = notes.filter((note) => note.title === title);
  console.log( "If you get message your input object was duplicated");
  if(duplicatesNotes.length === 0) {
      notes.push(note);
      saveNotes(notes);
      return note;
    }
};

module.exports = {
    addNote,
    logNote
};

所以我调用了两次node app.js --title="drunk" --body="weed",结果从title获取错误${note.title}未定义。

需要一些建议,谢谢你的阅读

1 个答案:

答案 0 :(得分:0)

try {
      var noteString = fs.readFileSync('notes-data.json');
      return JSON.parse(noteString);
  } catch (e) {
      return [];
  }

fs将返回缓冲区,并且您无法解析该缓冲区,必须先对缓冲区进行字符串化然后再解析。

var note=fs.readFileSync('notes-data.json')
var noteString=JSON.stringify(note)
return JSON.parse(noteString)