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

问题描述 投票:0回答:1

我创建了三个文件-contactPresentation.js,contactService.js,contacts.json。我将运行contactService.js文件。它将导航到contactPresentation.js文件,该文件仅选择添加或显示文件的选项。如果是add(),则将数据添加到服务文件的添加中。数据将被添加到contacts.json文件中。如果显示(),则显示服务文件的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, "[email protected]");

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

 []
javascript node.js json
1个回答
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, "[email protected]");
test.display(); 

当然,您需要从联系人Presentation.js中删除'evap'行,var test line和test.display行

就这么简单。

© www.soinside.com 2019 - 2024. All rights reserved.