#1. Node Modules

1. Node Modules의 개념

1) Node Module이란?

  • Node.js 안에 처음부터 내장되어 있는 모듈들을 말한다.
  • 자바스크립트의 내장 객체와는 다른 개념이다.

 

2) Module 호출 방법

- ES5 문법

const 참조명 = require('경로/파일이름');
  • require( ) 함수는 module.exports를 통해서 등록된 기능들을 리턴한다.
  • 리턴을 받는 객체는 module.exports에 확장된 기능들을 참조한다.
  • 파일 경로를 명시할 때는 확장자를 생략할 수 있다.
    • 하지만 동일 경로하 하더라고 ' ./ ' 는 생략할 수 없다.
    • ' ./ '가 생략되는 경우 node의 내장 모듈로 인식한다.
const example = require('./ExampleModule');

// 모듈형태로 참조된 함수를 호출
example();

 

- ES6 문법

import 참조명 from '모듈';
import 참조명 from '경로/파일이름.js';
  • Node에서 React의 import 구문처럼 사용할 수 있다. (ES6, Node14 버전 이후 import  구문을 지원)
  • 단, 파일이름 뒤에 확장자 명을 반드시 명시해줘야 한다. (안하면 에러 발생)

import path from 'path';
import example from './exampleModule.js';

// 모듈형태로 참조된 함수를 호출
example();
  • 직접 작성한 코드를 참조할 경우 ' ./ '' ../ ' 등의 경로를 반드시 적용해야 한다.
  • 모듈 이름 앞에 ' ./ ' 등의 경로 표시가 없는 경우 기본모듈 혹은 npm(yarn) 명령으로 설치한 오픈소스 모듈로 인식하고, 모듈 저장소를 탐색한다.

 

※ Node에서 ES6 문법 사용하는 방법

yarn init
  • ES6 문법을 사용하고자 하는 폴더에서 위의 명령어를 입력한다.
  • 명령어를 수행하면 pakage.json 이라는 파일이 생기는데, 그 안에 "type": "module" 을 입력한다.

  • 해당 내용을 기입하면 해당 폴더 및 하위 폴더에서 ES6 문법으로 사용할 수 있다.
    • ES5문법을 사용하면 에러가 발생한다.

 

2. Node Modules 사용

1) PATH 모듈

  • Node가 구동중인 컴퓨터 내의 경로를 관리하는 기능.
  • javascript의 location 객체가 페이지의 url을 관리한다면, Node의 path 모듈은 내 컴퓨터 안의 파일 경로를 관리한다.

- path 모듈 참조

import path from 'path';

 

- 경로 합치기

  • 파라미터의 제한이 없다.
  • 조합된 경로 문자열에 해당하는 path가 실제로 존재하는지는 상관없다.
const currentPath = path.join('/Users/hello/world', 'myphoto', '../photo.jpg');

console.debug('path.join >> ' + currentPath);

/* 출력
  path.join >> /Users/hello/world/photo.jpg
*/

 

- 경로에서 디렉토리, 파일명, 확장자 구분하기

const dirname = path.dirname(currentPath);    // 디렉토리
const basename = path.basename(currentPath);  // 파일이름
const extname = path.extname(currentPath);    // 확장자

console.debug('디렉토리 : %s', dirname);
console.debug('파일이름 : %s', basename);
console.debug('확장자 : %s', extname);

/* 출력
  디렉토리 : /Users/hello/world
  파일이름 : photo.jpg
  확장자 : .jpg
*/

 

- 경로정보 파싱

  • 경로 성분을 JSON 형태로 한번에 분할
const parse = path.parse(currentPath);

console.debug('%o', parse);

/* 출력
  {
    root: '/',
    dir: '/Users/hello/world',
    base: 'photo.jpg',
    ext: '.jpg',
    name: 'photo'
  }
*/

console.debug('root: ' + parse.root);
console.debug('dir: ' + parse.dir);
console.debug('name: ' + parse.name);
console.debug('ext: ' + parse.ext);

/* 출력
  root: /
  dir: /Users/hello/world
  name: photo
  ext: .jpg
*/

 

2) URL 모듈

  • url의 각 파트를 조회하거나, 파트별 값을 결합하여 완성된 url을 생성하는 기능. (location 객체와 비슷하다.)
  • url 모듈 내의 URL 클래스로 url 성분 정보를 확인하고, URLSearchParams로 querystring 부분을 추출할 수 있다.

1. URL

- url 모듈 참조

import { URL } from 'url';

 

- 주소 문자열을 URL 객체로 만들기

const myurl = 'http://localhost:3000/hello/world.html?a=123&b=456#home';

// URL의 각 성분을 분해 -> 자바스크립트 location 객체와 동일한 기능
const location = new URL(myurl);

console.debug(location);

/* 출력
 URL {
    href: 'http://localhost:3000/hello/world.html?a=123&b=456#home',
    origin: 'http://localhost:3000',
    protocol: 'http:',
    username: '',
    password: '',
    host: 'localhost:3000',
    hostname: 'localhost',
    port: '3000',
    pathname: '/hello/world.html',
    search: '?a=123&b=456',
    searchParams: URLSearchParams { 'a' => '123', 'b' => '456' },
    hash: '#home'
  }
*/

console.debug('href: ' + location.href);
console.debug('protocol: ' + location.protocol);
console.debug('host: ' + location.host);
console.debug('hostname: ' + location.hostname);
console.debug('port: ' + location.port);
console.debug('origin: ' + location.origin);
console.debug('pathname: ' + location.pathname);
console.debug('search: ' + location.search);
console.debug('hash: ' + location.hash);

/* 출력
  href: http://localhost:3000/hello/world.html?a=123&b=456#home
  protocol: http:
  host: localhost:3000
  hostname: localhost
  port: 3000
  origin: http://localhost:3000
  pathname: /hello/world.html
  search: ?a=123&b=456
  hash: #home
*/

 

2. URLSearchParams

- url 모듈 참조

import { URLSearchParams } from 'url';

 

- URL에서 querystring 부분만 추출

  • URL에서 추출한 모든 변수는 string 타입이다.
  • 추출할때는 get 방식을 사용한다.
const address = 'http://localhost:3000/hello/world.html?a=123&b=456';
const { searchParams } = new URL(address);

console.debug(searchParams);

/* 출력
  URLSearchParams { 'a' => '123', 'b' => '456' }
*/

console.debug('요청 파라미터 중 a의 값: %s', searchParams.get('a'));
console.debug('요청 파라미터 중 b의 값: %s', searchParams.get('b'));

/* 출력
  요청 파라미터 중 a의 값: 123
  요청 파라미터 중 b의 값: 456
*/

 

- JSON 객체를 querystring 문자열로 변환

  • URL에 포함될 수 없는 글자는 자동으로 인코딩 처리한다.
const obj = { name: 'chanCo', nick: 'JavaScript', address: '지구 어딘가'};

const str = new URLSearchParams(obj);
console.log('조합된 요청 파라미터: %s', str);

/* 출력
  조합된 요청 파라미터: name=chanCo&nick=JavaScript&address=%EC%A7%80%EA%B5%AC+%EC%96%B4%EB%94%98%EA%B0%80
*/

 

3) OS 모듈

  • Node가 구동중인 운영체제의 기본 정보들을 조회하는 기능.
  • 현재 컴퓨터의 메모리 사용량을 모니터링한다.
    • 현재 컴퓨터의 CPU정보, 수량, 성능, 모델명, 네트워크 등

- os 모듈 참조

import os from 'os';

 

- 시스템 기본 정보

console.debug('홈 디렉토리: ' + os.homedir);
console.debug('시스템 아키텍처: ' + os.arch);
console.debug('os플랫폼: ' + os.platform);
console.debug('시스템의 hostname: %s ', os.hostname);

/* 출력
  홈 디렉토리: /Users/chanco
  시스템 아키텍처: x64
  os플랫폼: darwin
  시스템의 hostname: Chanco-MacBook-Pro.local
*/

 

- 사용자 계정 정보

  • userInfo( )
const userInfo = os.userInfo();

console.debug('사용자 계정명: ' + userInfo.username);
console.debug('사용자 홈 디렉토리: ' + userInfo.homedir);
console.debug('사용자 쉘 환경: ' + userInfo.shell);
console.debug();

/* 출력
  사용자 계정명: chanco
  사용자 홈 디렉토리: /Users/chanco
  사용자 쉘 환경: /bin/zsh
*/

 

- 메모리 용량

  • freemem( ): 시스템에서 현재 사용 가능한 메모리 용량
  • totalmem( ): 시스템의 전체 메모리 용량
console.debug('시스템의 메모리: %d(free) / %d(total)', os.freemem(), os.totalmem());

/* 출력
  시스템의 메모리: 6700777472(free) / 17179869184(total)
*/

 

- cpu 정보

  • cpus( )
const cpus = os.cpus();

console.debug('CPU 코어 수: ' + cpus.length);

/* 출력
  CPU 코어 수: 8
*/

console.debug(cpus);

/* 출력
  [
    {
      model: 'Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz',
      speed: 2500,
      times: { user: 1375070, nice: 0, sys: 806930, idle: 4802660, irq: 0 }
    },
    {
      model: 'Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz',
      speed: 2500,
      times: { user: 403070, nice: 0, sys: 107050, idle: 6473930, irq: 0 }
    },
    {
      model: 'Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz',
      speed: 2500,
      times: { user: 1353210, nice: 0, sys: 656470, idle: 4974410, irq: 0 }
    },
    {
      model: 'Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz',
      speed: 2500,
      times: { user: 411070, nice: 0, sys: 81620, idle: 6491350, irq: 0 }
    },
    {
      model: 'Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz',
      speed: 2500,
      times: { user: 1164600, nice: 0, sys: 448890, idle: 5370590, irq: 0 }
    },
    {
      model: 'Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz',
      speed: 2500,
      times: { user: 428720, nice: 0, sys: 79730, idle: 6475590, irq: 0 }
    },
    {
      model: 'Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz',
      speed: 2500,
      times: { user: 1001910, nice: 0, sys: 327420, idle: 5654740, irq: 0 }
    },
    {
      model: 'Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz',
      speed: 2500,
      times: { user: 458410, nice: 0, sys: 73440, idle: 6452180, irq: 0 }
    }
  ]
*/

 

- 네트워크 정보

  • networkInterfaces()
const nets = os.networkInterfaces();

console.log(nets)

'국비수업 > Node.js' 카테고리의 다른 글

[Node.js] HTTP Client  (0) 2022.06.27
[Node.js] Scheduler  (0) 2022.06.27
[Node.js] Log  (0) 2022.06.27
[Node.js] Event / File Input Output  (0) 2022.06.24
[Node.js] Node.js 개념 이해하기  (0) 2022.06.23

+ Recent posts