program story

Node.js에있는 다른 파일의 JavaScript 클래스 정의 포함

inputbox 2020. 8. 30. 08:17
반응형

Node.js에있는 다른 파일의 JavaScript 클래스 정의 포함


Node.js에 대한 간단한 서버를 작성 중이며 User다음과 같은 자체 클래스를 사용하고 있습니다 .

function User(socket) {
    this.socket = socket;
    this.nickname = null;

    /* ... just the typical source code like functions, variables and bugs ... */

    this.write = function(object) {
        this.socket.write(JSON.stringify(object));
    }
};

그리고 나중에 프로세스를 많이 인스턴스화합니다.

var server = net.createServer(function (socket) {
    /* other bugs */
    var user = new User(socket);
    /* more bugs and bad practise */
});

User클래스 정의를 다른 자바 스크립트 파일 로 이동 하고 어떻게 든 "포함"할 수 있습니까?


간단하게 다음과 같이 할 수 있습니다.

user.js

class User {
    //...
}

module.exports = User

server.js

const User = require('./user.js')

// Instantiate User:
let user = new User()

2019 업데이트

ES 모듈이 표준이 되었기 때문에 일부 작성자는 Node.js가 ESM 사용을 허용하지 않기 때문에 혼란 스러울 수있는 기사에서이를 사용하고 있습니다. 그 동안 Node.js는 실험적인 지원을 제공하며 ESM이 작동하도록하려면 플래그가 필요합니다. Node.js의 ESM 문서 에서 이에 대해 읽어보십시오 .

다음은 설명을 위해 동일한 동작의 예입니다.

user.js

export default class User {}

server.js

import User from './user.js'

let user = new User()

노트

Don't use globals, it creates potential conflicts in the future.


Using ES6, you can have user.js:

export default class User {
  constructor() {
    ...
  }
}

And then use it in server.js

const User = require('./user.js').default;
const user = new User();

Modify your class definition to read like this:

exports.User = function (socket) {
  ...
};

Then rename the file to user.js. Assuming it's in the root directory of your main script, you can include it like this:

var user = require('./user');
var someUser = new user.User();

That's the quick and dirty version. Read about CommonJS Modules if you'd like to learn more.


Another way in addition to the ones provided here for ES6

module.exports = class TEST{
    constructor(size) {
        this.map = new MAp();
        this.size = size;

    }

    get(key) {
        return this.map.get(key);
    }

    length() {
        return this.map.size;
    }    

}

and include the same as

var TEST= require('./TEST');
var test = new TEST(1);

If you append this to user.js:

exports.User = User;

then in server.js you can do:

var userFile = require('./user.js');
var User = userFile.User;

http://nodejs.org/docs/v0.4.10/api/globals.html#require

Another way is:

global.User = User;

then this would be enough in server.js:

require('./user.js');

Instead of myFile.js write your files like myFile.mjs. This extension comes with all the goodies of es6, but I mean I recommend you to you webpack and Babel

참고URL : https://stackoverflow.com/questions/6998355/including-javascript-class-definition-from-another-file-in-node-js

반응형