■ Front-End ■/Node.js

[Node.js] 어디든지 사용 가능한 전역변수와 전역함수, 전역객체

한길(One Way) 2023. 2. 26.
Node.js는 빠르고 쉬우며 확장 가능한 JavaScript 런타임이다.

 

1. 개요

이번 시간에는 전역변수와 전역함수 그리고 전역객체에 대해서 알아보자.

Node.js는 실행 중인 프로그램 어디든지 접근할 수 있는 전역변수와 전역함수 그리고 전역객체가 있다.

2. 전역변수

전역변수는 일반적으로 지역 변수와 유사하다. 차이점은 사용할 수 있는 범위가 다르다.

코드 어디서나 사용할 수 있는 변수로 이름 앞에 언더바(_)가 두 개 있어 구분하기 편하다.

 

__filename : 현재 실행 중인 코드의 파일 경로

__dirname : 현재 실행 중인 코드의 폴더 경로

 

Node.js가 실행한 디렉터리와 실행한 파일명을 표시할 때 전역변수 __dirname와 __filename를 사용한다.

console.log("dir = " + __dirname);
console.log("file = " + __filename);

실행 결과

dir = D:\app\nodespace
file = D:\app\nodespace\06-global_var.js

3. 전역함수

전역함수는 실행 중인 코드 어디든지 사용할 수 있는 함수이다.

대표적으로 아래와 같은 타이머 함수들이 있다.

  • setInterval
  • clearInterval
  • setTimeout
  • clearTimeout

주기적인 반복 호출이 필요할 때 setInterval()를 사용한다. 반복을 멈출 때는 clearInterval()를 사용한다.

다음이 코드는 count start를 표시하고 1초 간격으로 count 변숫값을 출력하고 5가 되면 count End를 출력하고 끝난다.

console.time("Time") // 시간 측정 시작

var count = 0;
var repeat = setInterval(function() {
       count++;
       console.log("count = " + count);
       if (count == 5)
       {
               clearInterval(repeat);
               console.log("count End");
               console.timeEnd("Time") // 시간 측정 종료
       }
}, 1000);
 
console.log("count Start");

실행 결과

count Start
count = 1
count = 2
count = 3
count = 4
count = 5
count End
Time: 5.045s

4. 전역객체

언제나 사용할 수 있는 전역객체 process에 대해서 알아보자.

process 객체는 실행 중인 노드의 정보를 담고 있는 객체이다. 실행 시 인자에 대해서 출력하려면 process.argv를 이용하면 된다. 첫 번째 요소는 node이고 두 번째 요소는 js 파일명이다.

process.execPath는 node 실행파일의 절대 경로이고 process.version는 node의 버전을 나타낸다.

process.versions 는 node과 연관된 모듈들의 버전을 표시한다.

process.argv.forEach(function(val, index, array) {
       console.log("argv = " + index + " : " + val);
});
 
console.log();
console.log("process.execPath = ", process.execPath);
console.log("process.version = ", process.version);

console.log("process.versions\n");
console.dir(process.versions);

실행 결과

 
argv = 0 : D:\app\nodejs\node.exe
argv = 1 : D:\dev\enide\workspace\HelloNode\08-global_obj.js

process.execPath =  D:\app\nodejs\node.exe
process.version =  v16.16.0
process.versions

{
  node: '16.16.0',
  v8: '9.4.146.24-node.21',
  uv: '1.43.0',
  zlib: '1.2.11',
  brotli: '1.0.9',
  ares: '1.18.1',
  modules: '93',
  nghttp2: '1.47.0',
  napi: '8',
  llhttp: '6.0.7',
  openssl: '1.1.1q+quic',
  cldr: '40.0',
  icu: '70.1',
  tz: '2021a3',
  unicode: '14.0',
  ngtcp2: '0.1.0-DEV',
  nghttp3: '0.1.0-DEV'
}

 

process.memoryUsage()로 메모리 상태를 알 수 있다.

 
console.log("process.memoryUsage() = ", process.memoryUsage());
console.log("process.memoryUsage().rss:", process.memoryUsage().rss);
console.log("process.memoryUsage().heapTotal:", process.memoryUsage().heapTotal);
console.log("process.memoryUsage().heapUsed:", process.memoryUsage().heapUsed);

실행 결과

process.memoryUsage() =  {
  rss: 22151168,
  heapTotal: 4931584,
  heapUsed: 4082872,
  external: 309830,
  arrayBuffers: 11158
}
process.memoryUsage().rss: 22700032
process.memoryUsage().heapTotal: 5201920
process.memoryUsage().heapUsed: 4383416

process.env는 환경변수 정보를 표시한다.

console.dir(process.env);

실행 결과

{
  PATH: 'D:/app/jdk1.8.0_311/bin/../jre/bin/server;D:/app/jdk1.8.0_311/bin/../jre/bin;D:/app/jdk1.8.0_311/bin/../jre/lib/amd64;C:\\Program Files (x86)\\VMware\\VMware Workstation\\bin\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program Files (x86)\\NAT Service;C:\\Program Files\\Git\\cmd;D:\\app\\nodejs\\;D:\\app\\jdk1.8.0_311\\bin;D:\\app\\apache-maven-3.6.3\\bin;D:\\dev\\vscode\\bin;D:\\app\\nodejs;D:\\db\\MongoDB\\Server\\5.0\\bin;D:\\app\\apache-ant-1.10.12\\bin;D:\\app\\apache-tomcat-9.0.64\\bin;D:\\dev\\vscode\\bin;C:\\Users\\OneWay\\AppData\\Roaming\\npm;C:\\Program Files (x86)\\ESTsoft\\ALSee\\x64;D:\\dev\\enide;',
  SystemDrive: 'C:',
  SystemRoot: 'C:\\WINDOWS',
  TEMP: 'C:\\Temp',
  TMP: 'C:\\Temp'
}

process.config는 환경정보를 표시한다.

console.log("process.config\n");
console.dir(process.config);

실행 결과

{
  target_defaults: {
    cflags: [],
    default_configuration: 'Release',
    defines: [ 'NODE_OPENSSL_CONF_NAME=nodejs_conf' ],
    include_dirs: [],
    libraries: []
  },
  variables: {
    asan: 0,
    coverage: false,
    dcheck_always_on: 0,
    debug_nghttp2: false,
    debug_node: false,
    enable_lto: false,
    enable_pgo_generate: false,
    enable_pgo_use: false,
    error_on_warn: false,
    force_dynamic_crt: 0,
    host_arch: 'x64',
    icu_data_in: '..\\..\\deps\\icu-tmp\\icudt70l.dat',
    icu_endianness: 'l',
    icu_gyp_path: 'tools/icu/icu-generic.gyp',
    icu_path: 'deps/icu-small',
    icu_small: false,
    icu_ver_major: '70',
    is_debug: 0,
    llvm_version: '0.0',
    napi_build_version: '8',
    nasm_version: '2.15',
    node_byteorder: 'little',
    node_debug_lib: false,
    node_enable_d8: false,
    node_install_corepack: true,
    node_install_npm: true,
    node_library_files: [
      'lib/assert.js',
      'lib/async_hooks.js',
      'lib/buffer.js',
      'lib/child_process.js',
      'lib/cluster.js',
      'lib/console.js',
      'lib/constants.js',
      'lib/crypto.js',
      'lib/dgram.js',
      'lib/diagnostics_channel.js',
      'lib/dns.js',
      'lib/domain.js',
      'lib/events.js',
      'lib/fs.js',
      'lib/http.js',
      'lib/http2.js',
      'lib/https.js',
      'lib/inspector.js',
      'lib/module.js',
      'lib/net.js',
      'lib/os.js',
      'lib/path.js',
      'lib/perf_hooks.js',
      'lib/process.js',
      'lib/punycode.js',
      'lib/querystring.js',
      'lib/readline.js',
      'lib/repl.js',
      'lib/stream.js',
      'lib/string_decoder.js',
      'lib/sys.js',
      'lib/timers.js',
      'lib/tls.js',
      'lib/trace_events.js',
      'lib/tty.js',
      'lib/url.js',
      'lib/util.js',
      'lib/v8.js',
      'lib/vm.js',
      'lib/wasi.js',
      'lib/worker_threads.js',
      'lib/zlib.js',
      'lib/_http_agent.js',
      'lib/_http_client.js',
      'lib/_http_common.js',
      'lib/_http_incoming.js',
      'lib/_http_outgoing.js',
      'lib/_http_server.js',
      'lib/_stream_duplex.js',
      'lib/_stream_passthrough.js',
      'lib/_stream_readable.js',
      'lib/_stream_transform.js',
      'lib/_stream_wrap.js',
      'lib/_stream_writable.js',
      'lib/_tls_common.js',
      'lib/_tls_wrap.js',
      'lib/assert/strict.js',
      'lib/dns/promises.js',
      'lib/fs/promises.js',
      'lib/internal/abort_controller.js',
      'lib/internal/assert.js',
      'lib/internal/async_hooks.js',
      'lib/internal/blob.js',
      'lib/internal/blocklist.js',
      'lib/internal/buffer.js',
      'lib/internal/child_process.js',
      'lib/internal/cli_table.js',
      'lib/internal/constants.js',
      'lib/internal/dgram.js',
      'lib/internal/dtrace.js',
      'lib/internal/encoding.js',
      'lib/internal/errors.js',
      'lib/internal/error_serdes.js',
      'lib/internal/event_target.js',
      'lib/internal/fixed_queue.js',
      'lib/internal/freelist.js',
      'lib/internal/freeze_intrinsics.js',
      'lib/internal/heap_utils.js',
      'lib/internal/histogram.js',
      'lib/internal/http.js',
      'lib/internal/idna.js',
      'lib/internal/inspector_async_hook.js',
      'lib/internal/js_stream_socket.js',
      'lib/internal/linkedlist.js',
      'lib/internal/net.js',
      'lib/internal/options.js',
      'lib/internal/priority_queue.js',
      'lib/internal/promise_hooks.js',
      'lib/internal/querystring.js',
      'lib/internal/repl.js',
      'lib/internal/socketaddress.js',
      'lib/internal/socket_list.js',
      'lib/internal/stream_base_commons.js',
      'lib/internal/timers.js',
      'lib/internal/trace_events_async_hooks.js',
      'lib/internal/tty.js',
      'lib/internal/url.js',
      'lib/internal/util.js',
      'lib/internal/v8_prof_polyfill.js',
      'lib/internal/v8_prof_processor.js',
      ... 170 more items
    ],
    node_module_version: 93,
    node_no_browser_globals: false,
    node_prefix: '/usr/local',
    node_release_urlbase: 'https://nodejs.org/download/release/',
  
  ... (생략) ...
 
728x90

댓글