Nice programing

require가있는 Node.js ES6 클래스

nicepro 2020. 10. 14. 20:57
반응형

require가있는 Node.js ES6 클래스


그래서 지금까지 node.js다음과 같은 방식으로 클래스와 모듈을 만들었습니다 .

    var fs = require('fs');

var animalModule = (function () {
    /**
     * Constructor initialize object
     * @constructor
     */
    var Animal = function (name) {
        this.name = name;
    };

    Animal.prototype.print = function () {
        console.log('Name is :'+ this.name);
    };

    return {
        Animal: Animal
    }
}());

module.exports = animalModule;

이제 ES6를 사용하여 다음과 같이 "실제"수업을 만들 수 있습니다.

class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

자, 우선, 나는 이것을 좋아합니다 :) 그러나 그것은 질문을 제기합니다. 이것을 node.js의 모듈 구조 와 결합하여 어떻게 사용 합니까?

데모를 위해 모듈을 사용하려는 클래스가 있다고 가정 해 보겠습니다. fs

따라서 파일을 만듭니다.


Animal.js

var fs = require('fs');
class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

이것이 올바른 방법일까요?

또한이 클래스를 내 노드 프로젝트 내의 다른 파일에 어떻게 노출합니까? 별도의 파일에서 사용하는 경우에도이 클래스를 확장 할 수 있습니까?

여러분 중 일부가이 질문에 답할 수 있기를 바랍니다. :)


예, 귀하의 예는 잘 작동합니다.

클래스 노출에 관해서는 export다른 클래스와 마찬가지로 클래스를 사용할 수 있습니다.

class Animal {...}
module.exports = Animal;

또는 더 짧습니다.

module.exports = class Animal {

};

다른 모듈로 가져 오면 해당 파일에 정의 된 것처럼 처리 할 수 ​​있습니다.

var Animal = require('./Animal');

class Cat extends Animal {
    ...
}

ES5 방식으로 생성자 이름을 처리 한 것과 동일하게 ES6 클래스 이름을 처리하십시오. 그들은 하나이고 동일합니다.

ES6 구문은 단지 구문 적 설탕이며 정확히 동일한 기본 프로토 타입, 생성자 함수 및 객체를 생성합니다.

따라서 ES6 예제에서 다음을 사용하십시오.

// animal.js
class Animal {
    ...
}

var a = new Animal();

module.exports = {Animal: Animal};

Animal객체의 생성자처럼 취급 할 수 있습니다 (ES5에서했던 것과 동일). 생성자를 내보낼 수 있습니다. 를 사용하여 생성자를 호출 할 수 있습니다 new Animal(). 그것을 사용하는 모든 것이 동일합니다. 선언 구문 만 다릅니다. Animal.prototype당신의 모든 방법을 가지고 있는가 여전히 있습니다. ES6 방식은 실제로 더 멋지고 더 좋은 구문으로 동일한 코딩 결과를 생성합니다.


가져 오기 측에서는 다음과 같이 사용됩니다.

const Animal = require('./animal.js').Animal;

let a = new Animal();

이 체계는 Animal 생성자 .Animal를 해당 모듈에서 둘 이상의 것을 내보낼 수 있는 속성으로 내 보냅니다.

둘 이상의 항목을 내보낼 필요가없는 경우 다음을 수행 할 수 있습니다.

// animal.js
class Animal {
    ...
}

module.exports = Animal;

그리고 다음을 사용하여 가져옵니다.

const Animal = require('./animal.js');

let a = new Animal();

The ES6 way of require is import. You can export your class and import it somewhere else using import { ClassName } from 'path/to/ClassName'syntax.

import fs from 'fs';
export default class Animal {

  constructor(name){
    this.name = name ;
  }

  print(){
    console.log('Name is :'+ this.name);
  }
}

import Animal from 'path/to/Animal.js';

Using Classes in Node -

Here we are requiring the ReadWrite module and calling a makeObject(), which returns the object of the ReadWrite class. Which we are using to call the methods. index.js

const ReadWrite = require('./ReadWrite').makeObject();
const express = require('express');
const app = express();

class Start {
  constructor() {
    const server = app.listen(8081),
     host = server.address().address,
     port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port);
    console.log('Running');

  }

  async route(req, res, next) {
    const result = await ReadWrite.readWrite();
    res.send(result);
  }
}

const obj1 = new Start();
app.get('/', obj1.route);
module.exports = Start;

ReadWrite.js

Here we making a makeObject method, which makes sure that a object is returned, only if a object is not available.

class ReadWrite {
    constructor() {
        console.log('Read Write'); 
        this.x;   
    }
    static makeObject() {        
        if (!this.x) {
            this.x = new ReadWrite();
        }
        return this.x;
    }
    read(){
    return "read"
    }

    write(){
        return "write"
    }


    async readWrite() {
        try {
            const obj = ReadWrite.makeObject();
            const result = await Promise.all([ obj.read(), obj.write()])
            console.log(result);
            check();
            return result
        }
        catch(err) {
            console.log(err);

        }
    }
}
module.exports = ReadWrite;

For more explanation go to https://medium.com/@nynptel/node-js-boiler-plate-code-using-singleton-classes-5b479e513f74

참고URL : https://stackoverflow.com/questions/42684177/node-js-es6-classes-with-require

반응형