developer tip

NodeJS / Express에서“module.exports”와“exports.methods”는 무엇을 의미합니까?

optionbox 2020. 12. 29. 06:59
반응형

NodeJS / Express에서“module.exports”와“exports.methods”는 무엇을 의미합니까?


에 대한 프레임 워크 의 임의의 소스 파일보면 내가 이해하지 못하는 두 줄의 코드가 있습니다 (이 코드 줄은 거의 모든 NodeJS 파일에 일반적 임).expressNodeJS

/**
 * Expose `Router` constructor.
 */

exports = module.exports = Router;

/**
 * Expose HTTP methods.
 */

var methods = exports.methods = require('./methods');

나는 이해 코드의 첫 번째 조각 NodeJS 응용 프로그램에 노출 될 수있는 파일의 기능의 나머지 부분을 수 있지만, 정확히 이해가 안 돼요 어떻게 작동하는지 라인 수단의 코드를, 또는 무엇.

무엇을해야 exports하고 module.exports실제로 의미?

두 번째 코드는 파일의 함수가 .NET에 액세스 할 수 있도록 허용한다고 생각 methods하지만 정확히 어떻게 수행합니까?

기본적으로, 어떤이 마법의 단어는 다음과 같습니다 moduleexports?


더 구체적으로 말하면 :

module 파일 내의 전역 범위 변수입니다.

그래서 전화 require("foo")하면 :

// foo.js
console.log(this === module); // true

window브라우저에서 작동 하는 것과 동일한 방식으로 작동합니다.

또한 global원하는 파일에서 쓰고 읽을 수있는 또 다른 전역 개체가 있지만 전역 범위 변경이 포함되며 이것은 EVIL입니다.

exports에 존재하는 변수입니다 module.exports. 기본적으로 파일이 필요할 때 내보내는입니다.

// foo.js
module.exports = 42;

// main.js
console.log(require("foo") === 42); // true

exports자체적 으로 사소한 문제가 있습니다. _global 범위 컨텍스트 +하고 module있다 하지 동일. (브라우저에서 전역 범위 컨텍스트 window는 동일합니다).

// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with

// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the "correct" exports

// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works

수출에 대해 자세히 알아보기


Raynos의 답변을 확장하려면 ...

exports기본적으로 별칭 입니다 module.exports. 사용하지 않는 것이 좋습니다. 다음과 같이 on을 설정하여 모듈에서 메서드와 속성을 노출module.exports 할 수 있습니다 .

//file 'module1.js'
module.exports.foo = function () { return 'bar' }
module.exports.baz = 5

그런 다음 코드에서 액세스 할 수 있습니다.

var module1 = require('module1')
console.log(module1.foo())
console.log(module1.baz)

필요에 따라 단순히 단일 객체를 제공하도록 완전히 재정의 할 수도 있습니다module.exports .

//glorp.js
module.exports = function () {
  this.foo = function () { return 'bar' }
  this.baz = 5
  return this // need to return `this` object here
}

이제 멋진 프로토 타입이 생겼습니다.

var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz)

module.exports을 (를) 사용하는 다른 방법은 무수히 많습니다 require. 그냥 기억 require('foo') 항상 같은 인스턴스를 반환 여러 번 호출하더라도합니다.

노트

다음이 작동하려면

var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz) 

this에 할당 된 함수에서 반환되어야합니다 module.exports. 그렇지 않으면 다음이 표시됩니다 TypeError.

console.log(g1.foo())
          ^
TypeError: Cannot read property 'foo' of undefined

You can find the best answer in node.js source code. If someone is requiring your js module, your script turns into a function by node as follows (see src/node.js).

// require function does this..
(function (exports, require, module, __filename, __dirname) {
    ... your javascript contents...
});

Node will wrap your script. Then above script will be executed as follows:

//module.js
var args = [self.exports, require, self, filename, dirname];
return compiledWrapper.apply(self.exports, args);

So in your script,

exports is just module.exports.

In your script, you can add something to this exports object (functions..). require function will return this object. This is node.js's module system (commonJS specification).

But be careful not to modify module.exports. Otherwise your current exports will be meaningless.


module is an object that represents what that particular source file would like to publicly expose. Instead of having something akin to header files in the c/c++ world, you describe what the module exports by defining this object. the node runtime then uses this object to determine what about your module is 'public.'

its a similar concept to exporting functions from a dll in the compiled world. you have to define explicitly what functions can be accessed by the outside world. this helps with encapsulation and lets your organize your libraries in a clean way.


Module's code is wrapped in module.exports (The module, maybe composed by other module). There are many ways to build a module, but this is one very common (and my personal favorite).

// Dependencies
// const module = require('module');

// Module object
var foo = {}

// Internal property
foo._a = 'a';

// "Public" property
foo.b = 'b';

// Method
foo.fu = function() { return 'fu' };

// Export
module.exports = foo;

ReferenceURL : https://stackoverflow.com/questions/6116960/what-do-module-exports-and-exports-methods-mean-in-nodejs-express

반응형