본문 바로가기

Node.js(with codecademy) - 2

@sonic052025. 6. 17. 21:24

javascript 코드 실행

 

Node는 자바스크립트 프로그램을 콘솔이나 HTML안이 아닌, 내 컴퓨터에서 실행할 수 있다

 

 

1.app.js코드 적기

let noun1 = 'person';
let adjective = 'sleepy';
let noun2 = 'person';
let verb = 'sleep';
let noun3 = 'rice';

console.log(`The worlds first ${noun1} was 
a very ${adjective} ${noun2} who loved to 
${verb} while eating ${noun3} for every meal.`);

 

 

2.터미널에서 app.js 실행

$ node app.js
The worlds first person was a very
sleepy person who loved to sleep 
while eating rice for every meal.

 

 

Core Modules

모듈화는 프로그램을 여러개의 파일로 나눠서 기능별로 관리하는 기법이다.

Node.js는 이를 지원하며 자주 쓰이는 기능들을 미리 내장시켜 놓았는데 이를 Core Module(코어 모듈)이라고 한다.

 

아래와 같이 불러와 사용할 수 있다.

const events = require('events');

 

 

1.Node REPL에 들어가기

$ node
Welcome to Node.js v14.19.1.
Type ".help" for more information.
>

 

 

2.REPL에서 기본 내장된 모든 코어 목록 출력

> 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',
  'async_hooks',       'buffer',              'child_process',
  'cluster',           'console',             'constants',
  'crypto',            'dgram',               'diagnostics_channel',
  'dns',               'domain',              'events',
  'fs',                'fs/promises',         'http',
  'http2',             'https',               'inspector',
  'module',            'net',                 'os',
  'path',              'perf_hooks',          'process',
  'punycode',          'querystring',         'readline',
  'repl',              'stream',              'string_decoder',
  'sys',               'timers',              'tls',
  'trace_events',      'tty',                 'url',
  'util',              'v8',                  'vm',
  'wasi',              'worker_threads',      'zlib'
]
>

 

 

Console 모듈

 

 

Console모듈을 활용하여 터미널을 통해 메시지를 주고받음

  • console.log(): 일반 텍스트 출력
  • console.assert():조건이 false일때만 메세지 출력(조건,메시지) - 인자 2개
  • console.table():배열이나 객체를 테이블 형태로 출력

 

app.js

const petsArray = ['dog', 'cat', 'bird', 'monkey'];

// Add console methods below!
console.log(petsArray);
console.table(petsArray);
console.assert(petsArray.length > 5);

 

 

결과(터미널)

[ 'dog', 'cat', 'bird', 'monkey' ]
┌─────────┬──────────┐
│ (index) │  Values  │
├─────────┼──────────┤
│    0    │  'dog'   │
│    1    │  'cat'   │
│    2    │  'bird'  │
│    3    │ 'monkey' │
└─────────┴──────────┘
Assertion failed

 

 

 

process

 

실행중인 프로그램 하나하나를 프로세스라고 한다.

process라는 전역 객체를 통해, 현재 실행중인 프로그램에 대한 정보나 제어기능 제공

process.env 현재 환경 변수들을 담고 있는 객체 (NODE_ENV, PWD 등)
process.memoryUsage() 메모리 사용량 정보를 반환 (heapUsed 등)
process.argv 실행할 때 함께 입력한 커맨드라인 인자들을 배열로 담고 있음

 

 

메모리 변화 및 명령어 저장 예제

//메모리 기록1
let initialMemory = process.memoryUsage().heapUsed;

//터미널에 친 명령어중 2번쨰 index에 있는 것을 가져와서 저장 후 출력
let word = process.argv[2];
console.log(`Your word is ${word}`)

// Create a new array
let wordArray = [];

// Loop 1000 times, pushing into the array each time 
for (let i = 0; i < 1000; i++){
  wordArray.push(`${word} count: ${i}`)
}

//메모리기록2를 한 후 메모리기록2에서 메모리기록1을 뻄
console.log(`Starting memory usage: ${initialMemory}. 
\nCurrent memory usage: ${process.memoryUsage().heapUsed}. 
\nAfter using the loop to add elements to the array, 
the process is using ${process.memoryUsage().heapUsed - initialMemory} 
more bytes of memory.`)

 


 

정리

    • app.js를 단독 파일로 실행할 수 있다.(html 등 내부에 넣을 필요X)
    • core modules(라이브러리랑 비슷)
    • console(모듈 중 하나로 터미널으로 메시지 주고받음)
    • process(모듈 중 하나로 시스템 정보를 다룸 / 메모리 사용량, 실행 인자, 환경변수 등)

'개발' 카테고리의 다른 글

Node.js(with codecademy) - 5  (0) 2025.06.20
Node.js(with codecademy) - 4  (0) 2025.06.19
Node.js(with codecademy) - 3  (2) 2025.06.18
백준 11650 - 좌표정렬하기  (0) 2025.06.17
sonic05
@sonic05 :: sonic05 님의 블로그

sonic05 님의 블로그 입니다.

공감하셨다면 ❤️ 구독도 환영합니다! 🤗

목차