使用NodeJS中的类将联系人从server.js文件存储到json文件中

时间:2018-11-24 10:53:15

标签: javascript node.js json

我创建了三个文件-contactPresentation.js,contactService.js,contacts.json。我将运行contactService.js文件。它将导航到contactPresentation.js文件,该文件只会选择添加或显示文件的选项。如果使用add(),则将数据添加到服务文件的添加中,然后数据将被添加到contacts.json文件中。如果是display(),则显示服务文件的display()。显示屏将从contacts.json文件中获取数据。但是,我知道我的代码有缺陷。请更正它。我也遇到错误-

        this.contacts.push(new ContactService(userName, contactNumber, emailId));
                      ^

TypeError: Cannot read property 'push' of undefined
    at ContactService.add (e:\NodeJSProject\contactManager2\contactService.js:57:23)
    at new ContactService (e:\NodeJSProject\contactManager2\contactService.js:31:14)
    at Object.<anonymous> (e:\NodeJSProject\contactManager2\contactService.js:96:12)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)

contactService.js

const fs = require('fs');

var uuid = require('uuid');
const uuidv1 = require('uuid/v1');



console.log(uuid.v1());

eval(fs.readFileSync('contactPresentation.js').toString())

class ContactService {

    constructor(userName, contactNumber, emailId) {


        uuidv1();
        this.id = uuid.v1();
        this.firstName = userName;
        this.contactNo = contactNumber;
        this.email = emailId;
        this.add(userName, contactNumber, emailId)
    }

    get UUID() {  
        return this.id;
    }

    get name() {
        return this.firstName;
    }

    get contact() {
        return this.contactNo;
    }

    get emailID() {
        return this.email;
    }
    display() {

        loadFromFile();
        return this.contacts;
    }

    add(userName, contactNumber, emailId) {

        this.contacts.push(new ContactService(userName, contactNumber, emailId));

        saveToFile();

    }

    saveToFile() {

        let data = [];

        data.push(JSON.stringify(this.contacts, null, 2));

        fs.writeFile('contacts.json', data, (err) => {
            if (err) throw err;
            console.log('Data written to file');
        });

        console.log('This is after the write call');

    }

    loadFromFile() {   

        fs.readFile('contacts.json', (err, data) => {
            if (err) throw err;
            var contact = JSON.parse(data);
            console.log("contacts", contact);
        });

        console.log('This is after the read call');
    }

}

var test = new ContactService("abc",900, "abc@cateina.com");

test.display();
module.exports = ContactService

contactPresentation.js

contactService = require('./contactService.js')
var readlineSync = require('readline-sync');


var option = readlineSync.question(`What would you like to do, Add or Display Contact.
For Add , type 1, for display type 2 `);


class ContactPresentation {

    constructor(option) {

        abc = true;
        createService = new ContactService();


        while (abc) {
            if (option == 1) {


                var userName = readlineSync.question('May I have your name? ');

                console.log('Hi ' + userName + '!');

                var contactNumber = readlineSync.question('May I have your contact number');

                var emailId = readlineSync.questionEMail();

                createService.add(userName, contactNumber, emailId);

            }
            else if (option == 2) {
                createService.display();
            }

        }
    }
}

module.exports = ContactPresentation;

contacts.json

 []

1 个答案:

答案 0 :(得分:1)

您必须取消声明

this.contacts = [];

在您的contactService构造函数中。

此外,要开始执行您在评论中要求的操作,您的index.js如下所示:

const ContactPresentation = require('contactPresentation.js');
const ContactService = require('contactService.js');

// to run contactPresentation
const cp = new ContactPresentation();

// to run display the content of Presentation file
var test = new ContactService("abc",900, "abc@cateina.com");
test.display(); 

当然,您需要从contactPresentation.js中删除“ eval”行,var测试行和test.display行

就这么简单。