5 minute read

NPM(Node package manager)

자바스크립트의 패키지 매니저는 Node.js의 실행환경(runtime)에서 수행하며 프로젝트가 의존(dependency)하고 있는 패키지를 효과적으로 설치, 갱신, 삭제를 할 수 있도록 도와주는 도구를 의미한다. 대표적으로는 npm, yarn이 있다.

NPM 초기화

: NPM을 사용하기위해 초기화한다. (패키지 매니저 관련 파일들을 생성한다.)

# 1. 간편 설정 (모든 것을 Default로 설정)
$ npm init -y 

# 2. (모든 것을 수동으로 설정)
$ npm init

# npm init 후 만들어진 npm의 의존성을 관리하는 파일(package.json)
$ ls 
package.json

  • npm init 은 (npm 으로 동작하는) project 를 초기화해주는 명령어다.
  • npm init을 한곳이 한개의 프로젝트라고 보면 된다.
  • node.js에서 모듈관리는 npm(Node package manager)를 통해서 이루어진다.
  • npm은 통해서 설치, 업데이트, 삭제 ,프로젝트의 의존성을 관리 할 수 있다.
  • npm으로 모듈을 관리 하기 위해서는 생성한 프로젝트에서 npm init을 해주면 된다.

NPM 관련 파일

pacakage.json
프로젝트에서 사용되고 있는 패키지를 관리하는 JSON 형태의 파일.
pacakage-lock.json / yarn.lock
프로젝트 내에서 팀원들 간에 서로 다른 버전을 설치하지 않고, 동일한 버전을 설치하는 것을 보장하도록 명시된 패키지 잠금 파일.
pacakage-lock.json
npm 패키지 매니저를 사용 할 경우 사용되는 패키지 잠금 파일.
yarn.lock
yarn 패키지 매니저를 사용 할 경우 사용되는 패키지 잠금 파일.
node_modules
pacakge.json 파일에 명시된 패키지에 따라서 설치 된 패키지 디렉토리.

pacakage.json 파일

: 디폴트 + express 모듈 설치

{
  "name": "nodestudy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

  • dependencies 옵션
    프로젝트에서 의존하고 있는 일반적인 종속성이거나 코드를 실행하는데 사용하는 패키지들을 포함하고 있으며, 이 의존성 패키지는 컴파일을 수행하고 런타임 단계에서까지 수행되는 패키지들이 이에 해당 된다.
  • devDependencies
    💡 프로젝트에서 개발과 테스트 단계에서만 사용이 되는 패키지를 포함하고 있으며, 이 의존성 패키지는 컴파일 내에서만 수행되고 런타임 단계에서는 수행되지 않는 패키지들이 이에 해당 된다.
    ex) prettier, eslint, @types/xxx
  • peerDependencies
    💡 런타임에는 필요하기는 하지만 소스코드내에 의존성을 직접 관리하지 않는 라이브러리들이 포함된다. 소스코드 내에 require , import로 불러오지는 않지만 라이브러리 의존성으로 필요한 경우가 이에 해당 된다.
    ex) 플러그 인

pacakage-lock.json 파일

: 디폴트 모듈 명세가 너무 길어서 express 모듈을 설치한 상태에서 기록되 내용만 보면 아래와 같다.

{
  "name": "nodestudy",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "nodestudy",
      "version": "1.0.0",
      "license": "ISC",
      "dependencies": {
        "express": "^4.18.2"
      }
    },
    "node_modules/express": {
      "version": "4.18.2",
      "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz",
      "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==",
      "dependencies": {
        "accepts": "~1.3.8",
        "array-flatten": "1.1.1",
        "body-parser": "1.20.1",
        "content-disposition": "0.5.4",
        "content-type": "~1.0.4",
        "cookie": "0.5.0",
        "cookie-signature": "1.0.6",
        "debug": "2.6.9",
        "depd": "2.0.0",
        "encodeurl": "~1.0.2",
        "escape-html": "~1.0.3",
        "etag": "~1.8.1",
        "finalhandler": "1.2.0",
        "fresh": "0.5.2",
        "http-errors": "2.0.0",
        "merge-descriptors": "1.0.1",
        "methods": "~1.1.2",
        "on-finished": "2.4.1",
        "parseurl": "~1.3.3",
        "path-to-regexp": "0.1.7",
        "proxy-addr": "~2.0.7",
        "qs": "6.11.0",
        "range-parser": "~1.2.1",
        "safe-buffer": "5.2.1",
        "send": "0.18.0",
        "serve-static": "1.15.0",
        "setprototypeof": "1.2.0",
        "statuses": "2.0.1",
        "type-is": "~1.6.18",
        "utils-merge": "1.0.1",
        "vary": "~1.1.2"
      },
      "engines": {
        "node": ">= 0.10.0"
      }
    }
  }
}

node_modules 디렉토리

: 디폴트

$ cd nodeStudy/node_modules/
$ ls
accepts              depd          function-bind      methods         proxy-addr      statuses
array-flatten        destroy       get-intrinsic      mime            qs              toidentifier
body-parser          ee-first      has                mime-db         range-parser    type-is
bytes                encodeurl     has-symbols        mime-types      raw-body        unpipe
call-bind            escape-html   http-errors        ms              safe-buffer     utils-merge
content-disposition  etag          iconv-lite         negotiator      safer-buffer    vary
content-type         express       inherits           object-inspect  send
cookie               finalhandler  ipaddr.js          on-finished     serve-static
cookie-signature     forwarded     media-typer        parseurl        setprototypeof
debug                fresh         merge-descriptors  path-to-regexp  side-channel

[ 더 알아가기 ]
💡 Github Repository에 ‘node_modules’ 디렉토리를 올리지 않는 이유?

  • package.json에 명시된 패키지 목록과 lock파일에 지정된 버전만 있다면 모든 개발자가 동일한 버전에서 프로젝트를 구성 할 수 있기에 용량이 큰 node_modules 파일은 올리지 않는다.
  • 하지만 폐쇄망 환경이라면 모듈 디렉토리를 올리는 것은 의미가 있다. (현재 내가 그렇다.)

pacakage.json 버전을 관리

시맨틱 버저닝(Semantic Versioning)

: Node.js, npm, yarn은 시멘틱 버저닝을 채택하여서 패키지의 버전을 관리 한다.

사진1

:용어: :정의: :구조:
MAJOR 버전 API 호환성이 깨질만한 변경사항 [MAJOR].[MINOR].[PATCH] x.0.0 버전이 업데이트 되는것을 의미한다.
MINOR 버전 일반적인 업데이트(기능 추가)를 수행할때 진행된다. [MAJOR].[MINOR].[PATCH] .x.0 버전이 업데이트 되는것을 의미한다.
PATCH 버전 단순한 버그 해결을 위한 업데이트를 위해서 진행이 된다. [MAJOR].[MINOR].[PATCH] 0.0.x 버전이 업데이트 되는것을 의미한다.

Node.js 모듈에 대하여

: npm에 업로드된 노드 모듈을 패키지라고 부른다. 모듈이 다른 모듈을 사용할 수 있는 것처럼, 패키지도 다른 패키지를 사용할 수 있다. 이러한 관계를 의존 관계라고 한다.

참고한 블로그 링크)
https://doitnow-man.tistory.com/161

모듈 종류

Core 모듈

  • node.js 에서 기본적으로 제공하는 모듈

third party 모듈

  • npm(Node Packaged Modules)으로 설치한 모듈(node_modules 폴더 아래 설치된다.)
  • 종류는 너무 많아 (https://www.npmjs.com/) 여기서 찾는게 좋다.

local 모듈

  • 사용자가 만든 모듈

모듈 설치 방법

Core 모듈

  • 기본적으로 node.js 에서 제공하기에 설치가 필요 없다.
  • require(“module”).builtinModules 로 확인 가능하다.

      $ require('module').builtinModules
      [
        '_http_agent',         '_http_client',        '_http_common',
        '_http_incoming',      '_http_outgoing',      '_http_server',
        '_stream_duplex',      '_stream_passthrough', '_stream_readable',
        '_stream_transform',   '_stream_wrap',        '_stream_writable',
        '_tls_common',         '_tls_wrap',           'assert',
        'assert/strict',       'async_hooks',         'buffer',
        'child_process',       'cluster',             'console',
        'constants',           'crypto',              'dgram',
        'diagnostics_channel', 'dns',                 'dns/promises',
        'domain',              'events',              'fs',
        'fs/promises',         'http',                'http2',
        'https',               'inspector',           'module',
        'net',                 'os',                  'path',
        'path/posix',          'path/win32',          'perf_hooks',
        'process',             'punycode',            'querystring',
        'readline',            'readline/promises',   'repl',
        'stream',              'stream/consumers',    'stream/promises',
        'stream/web',          'string_decoder',      'sys',
        'timers',              'timers/promises',     'tls',
        'trace_events',        'tty',                 'url',
        'util',                'util/types',          'v8',
        'vm',                  'worker_threads',      'zlib'
      ]
      >
        
    

third party 모듈

  • node.js 에서 모듈 관리는 npm을 통해서 이루어 진다.
  • npm을 통해서 설치, 업데이트, 삭제 를 할 수 있다.

      # 설치 
      $ npm install -g [모듈명]  # global 설치 (모든 프로젝트에서 사용 가능) 
      $ npm install [모듈명]  # local 설치 (설치되는 위치는 프로젝트 하위의 node_modules에 설치. 해당 프로젝트만 사용가능)
            
      # 삭제 
        $ npm uninstall [모듈명]
    
      # 업데이트 
        $ npm update [모듈명]
    
      # 검색
        $ npm search [모듈명]
            
    

    npm으로 install 또는 uninstall 할때 마다 모듈이 dependencies 에 추가 되거나 삭제가 된다.

  • local 모듈
    • local 모듈을 만들어 주어야한다.
    • 사용자가 만든것이기 때문에 설치 할 필요가 없다.

모듈 설치경로

Core 모듈

  • 내장 모듈이다. 해당없음

third party 모듈

  1. Core 모듈
    • 내장모듈이다. 해당없음
  2. third party 모듈

    • global 설치 위치

        C:\Users\mt01301\AppData\Roaming\npm\node_modules
                
      
    • local 설치 위치

      • 현재 프로젝트하위의 node_modules 에 설치가 된다.
  3. local 모듈
    • 사용자가 만든것 이기 때문에 지정하기 나름이다.

모듈 검색 순서

: 모듈을 생성했는데 모듈을 찾지 못 할 경우 node.js에서 어떤 순서로 모듈을 찾는지 알 필요가 있다.

global 모듈 검색 위치

npm -g root
C:\Users\mt01301\AppData\Roaming\npm\node_modules  

third party 모듈 또는 local 모듈 검색 위치

# 현재 경로에서 하단계씩 올라가면서 node_modules를 찾는다.

$ node -e "console.log(global.module.paths)"  
[ 
'C:\\User\\MT01301\\node_modules', 
'C:\\User\\node_modules',
'C:\\node_modules'
]
       

모듈 호출

const module1 = require("core모듈명")

module1.모듈();

로컬 모듈 예제

local 모듈이란?
사용자가 코드관리는 위해 기능적으로 코드를 분리한 코드를 모듈이라고 한다.

로컬모듈 생성

  • node.js에서 모듈은 파일 하나를 의미 한다.
  • 모듈 파일에서 exports 객체에 메소드 및 프로퍼티를 추가 하면 해당 파일은 모듈로써 사용하겠다는 의미이다.

      touch module.js
      vi module.js
    
    

    module.js

      exports.module_name = 'test_module.js' // module_name 이라는 모듈을 exports 했다.
    
      exports.abs = function(number) {  // abs() 이라는 익명메소드 모듈을 exports 했다.
          if (0 < number) {
              return number;
          } else {
              return -number;
          }
      };
        
      exports.circleArea = function (radius) {  // circleArea() 이라는 익명메소드 모듈을 exports 했다.
          return radius * radius * Math.PI;
      }
        
    

exports하여 아래와 같이 필요한 곳에서 랩핑하여 쉽게 사용할 수 있다.

로컬모듈 사용

  • require(‘모듈파일명’)를 통하여 모듈을 로드 하여 사용 가능 하다.

      // 상기 모듈코드에서 만든 메소드(abs, circleArea), 프로퍼티(module_name)을 사용한 예제 이다.
        
      var module = require('./module.js');  //방금 생성한 로컬모듈을 호출했다.
        
      // 이렇게 모듈에 정의된 내용이 실행가능하다.
      console.log(module.abs(1));
      console.log(module.circleArea(1)); 
      console.log(module.module_name)
      
    

    결과

      # 결과 
      PS D:\jk_nodejs> node .\node_test.js
      1
      3.141592653589793
      test_module.js
    
    

Leave a comment