찾다

nodejs 모듈이 뭔가요?

Oct 29, 2021 pm 03:23 PM
nodejs기준 치수

모듈은 Node.js 애플리케이션의 기본 구성 요소입니다. 파일과 모듈은 일대일 대응입니다. Nodejs 모듈은 파일이며 이 파일은 JavaScript 코드, JSON 또는 컴파일된 "C/C++" 확장일 수 있습니다. . "require('파일 경로')" 문을 사용하여 모듈을 참조할 수 있습니다.

nodejs 모듈이 뭔가요?

이 튜토리얼의 운영 환경: windows7 시스템, nodejs 버전 12.19.0, Dell G3 컴퓨터.

Node.js 파일이 서로 호출할 수 있도록 Node.js에서는 간단한 모듈 시스템을 제공합니다.

모듈은 Node.js 애플리케이션의 기본 구성 요소이며 파일과 모듈은 일대일 대응을 갖습니다. 즉, Node.js 파일은 JavaScript 코드, JSON 또는 컴파일된 C/C++ 확장일 수 있는 모듈입니다.

nodejs의 경우 파일은 인터페이스를 내보내거나 다른 모듈이 들어오도록 요구할 수 있습니다.

// module1.js
exports.func1 = function(){
        console.log('func1 from module1 called');
}

module1은 내보내기 객체를 통해 모듈의 공개 액세스 인터페이스로 func1 함수를 사용합니다.

//module2.js
var in_module1 = require('./module1.js');
in_module1.func1();
exports.func2 = function(){
        console.log('func2 from module2 called');
}

module2에는 module1이 필요합니다. 이때 in_module1은 module1의 내보내기 개체와 동일합니다. in_module1을 사용하여 func1을 호출하는 것은 module1의 내보내기 개체를 통해 func1을 호출하는 것과 같습니다.

동시에 module2의 자체 함수 func2는 모듈의 내보내기 객체를 통해 module2 공개 인터페이스 역할도 합니다.

// module3.js
var in_module2 = require('./module2.js');
in_module2.func2();

마찬가지로 module3에는 module2가 필요합니다. 이때 in_module2는 module2의 내보내기 개체와 동일합니다.

실행 결과는 다음과 같습니다.

rlan@rlan-LA:~/nodejs/nodetest$ node module2.js
func1 from module1 called
rlan@rlan-LA:~/nodejs/nodetest$ node module3.js
func1 from module1 called
func2 from module2 called

nodejs에 의해 도입된 모듈은 모듈의 공개 인터페이스를 얻을 뿐만 아니라 파일의 다른 명령문도 참조합니다. 예:

module1.js가

// module2.js
console.log('this is in module2');
var in_module1 = require('./module1.js');
  
in_module1.func1();
  
exports.func2 = function(){
       console.log('func2 from module2 called');
}
로 변경되었습니다.

module2는 module1을 소개합니다. func1 함수는 module1의 print 문도 실행합니다.

rlan@rlan-LA:~/nodejs/nodetest$ node module1.js
this is in module1
rlan@rlan-LA:~/nodejs/nodetest$ node module2.js
this is in module2         - module2 self
this is in module1         - require module1
func1 from module1 called  - module2 self

이제, module2가 module1을 로드하고, module3이 module2를 로드합니다. module3이 module1을 다시 로드하면 어떻게 될까요?

// module3.js
var in_module1 = require('./module1.js');
var in_module2 = require('./module2.js');

in_module1.func1();
in_module2.func2();

이때, module3는 module1을 먼저 로드하고, module2는 module2 자체가 module1의 일부를 로드합니다. 실행 결과는

rlan@rlan-LA:~/nodejs/nodetest$ node module3.js
this is in module1        -  require module1
this is in module2        -  require module2
func1 from module1 called -  require module2
func1 from module1 called -  module3 self
func2 from module2 called -  module3 self

module3의 require 순서를 조정한 경우:

// module3.js
var in_module2 = require('./module2.js');
var in_module1 = require('./module1.js');

in_module1.func1();
in_module2.func2();

실행 결과는 다음과 같습니다.

rlan@rlan-LA:~/nodejs/nodetest$ node module3.js
this is in module2         - require module2
this is in module1         - require module2
func1 from module1 called  - require module2
func1 from module1 called  - module3 self
func2 from module2 called  - module3 self

nodejs는 동일한 모듈이 다른 모듈에 반복적으로 로드되지 않도록 하기 위해 어떤 메커니즘을 사용하는 것 같습니다. 따라서 module3.js에서는 두 번 로드되는 것처럼 보이지만

this is in module1

줄은 한 번만 나타납니다.

그렇다면 루프 로딩이 발생하면 어떻게 될까요? 이제 module1이 module2를 요구하도록 합니다.

// module1.js
console.log('this is in module1');

var in_module2 = require('./module2.js');

exports.func1 = function(){
        console.log('func1 from module1 called');
}
// module2.js
console.log('this is in module2');
var in_module1 = require('./module1.js');

in_module1.func1();

exports.func2 = function(){
        console.log('func2 from module2 called');
}

실행 결과는 다음과 같습니다.

rlan@rlan-LA:~/nodejs/nodetest$ node module1.js
this is in module1
this is in module2
/home/rlan/nodejs/nodetest/module2.js:4
in_module1.func1();
           ^
TypeError: in_module1.func1 is not a function
    at Object.<anonymous> (/home/rlan/nodejs/nodetest/module2.js:4:12)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:417:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/home/rlan/nodejs/nodetest/module1.js:3:18)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:417:10)
rlan@rlan-LA:~/nodejs/nodetest$ node module2.js
this is in module2
this is in module1
func1 from module1 called

nodejs가 module2를 실행할 때 module2를 로드하지 않는 동작은 module1이 module2를 로드하지 않는 결과와 동일합니다. 오류가 보고됩니다. module1을 실행할 때 module2로 가서 require module1 문을 무시하면 module2가 module1의 func1을 호출하고 프로그램이 잘못되었습니다.

요약하자면, nodejs에서 모듈을 반복적으로 로드(또는 자체 로드)하는 중첩된 require 문은 올바르게 실행될 수 없습니다.

【추천 학습: "nodejs tutorial"】

위 내용은 nodejs 모듈이 뭔가요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
React의 한계는 무엇입니까?React의 한계는 무엇입니까?May 02, 2025 am 12:26 AM

반응 말 : 1) asteeplearningcurveduetoitsvastecosystem, 2) Seochallengswithclient-siderendering, 3) PlatiperFormanceIssUseInlargeApplications, 4) ComplexStateManagementAsAppSgrow, 및 5) theneedTokeEpupWithitsHouou

React의 학습 곡선 : 새로운 개발자를위한 도전React의 학습 곡선 : 새로운 개발자를위한 도전May 02, 2025 am 12:24 AM

ReactisChallengingforbeginnersdueToitssteePlearningCurveanDParadigMshiftTocomponent 기반 Architection.1) 시작된 문서화 forasolidFoundation.2) startWithOficialDocumentationForAsolIdfoundation.2) 이해를 이해하는 방법

React에서 동적 목록을위한 안정적이고 고유 한 키 생성React에서 동적 목록을위한 안정적이고 고유 한 키 생성May 02, 2025 am 12:22 AM

thecorechallengeenderatingStableanduniquekysfordynamiclistsinconsengingconsententifiersacrossre-rendersforefficialdomupdates

JavaScript 피로 : React 및 그 도구로 최신 상태를 유지합니다JavaScript 피로 : React 및 그 도구로 최신 상태를 유지합니다May 02, 2025 am 12:19 AM

JavaScriptFatigueInreactismanageablewithstrestriveStriveStriveStiMelearningandcuratedInformationSources.1) 1))

usestate () 후크를 사용하는 테스트 구성 요소usestate () 후크를 사용하는 테스트 구성 요소May 02, 2025 am 12:13 AM

TOTESTREACTCOMPONENTSUSINSUSISTATEHOOK, useJestAndReactTestingLibraryTosimulationInteractionsandStateChangeSintheUI.1) renderTheComponentAndCheckInitialState.2) SimulateUserActionSlikeClickSorformSubMissions.3) verifyTateRecerFectsin

React의 키 : 성능 최적화 기술에 대한 깊은 다이빙React의 키 : 성능 최적화 기술에 대한 깊은 다이빙May 01, 2025 am 12:25 AM

keysinReactareCrucialforopiTizingPerformanceByIningIneficiveliceListEpdates.1) uskeyStoIndifyAndTrackListElements.2) revingArrayIndiceSkeyStopReverFormanceSues.3) 선택 가능한 식당 LikeItesteM.idtomaintaintAteAndimProvePerform

React의 열쇠는 무엇입니까?React의 열쇠는 무엇입니까?May 01, 2025 am 12:25 AM

RenderingListStoimproverCiliationeficiency를 사용하면 RECTKEYSAREUNIQUEINDIFIERSEDS (1) ISHELPREACTTRACKCHANGENLISTEMS, 2) 사용 ASSABLEANDUNICEIDERIDERSISTEMIDSISRECEMENDEND, 3) RepoySingArrayIndicesAskeyStopReventIsseswithReAdering 및 4) ENS

React에서 고유 키의 중요성 : 일반적인 함정 방지React에서 고유 키의 중요성 : 일반적인 함정 방지May 01, 2025 am 12:19 AM

고유 한 KeysAreCrucialInreactforoptoropiTizing and ComponentStateIntegrity

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기