FrontEnd/Node.js

[Node] Node 내장 객체, console, timer 객체

ss__jae2 2022. 11. 23. 17:24
반응형

Node 내장 객체 : 노드에서 자주 사용되는 객체로 미리 만들어져 있는 객체를 말함

 

1. 기본적인 객체

  • global
    - global은 브라우저의 window와 같은 전역 객체이다.
    - 따라서 모든 파일에서 접근 가능한 객체이고, global은 생략가능하다.
    - require, cosnole도 모두 global이 생략된 것이다.
  • __filename
    - 현재 실행 중인 파일의 경로를 알려준다.
    - console.log(__filename)
  • __dirname
    - 현재 실행 중인 폴더 경로를 알려준다.
    - console.log(__dirname)
  • path
    - path 모듈은 파일 명을 얻거나 운영체제별 경로 구분자가 달라 생기는 문제를 쉽게 해결하기 위해 만들어졌다.
    - Windows: c:\Users\ano 처럼 \를 사용해 폴더를 구분
    - UNIX : /user/ano 처럼 /를 사용해 폴더를 구분

    const path = require("path") : import 필요
  • timer
    - 지금 바로 실행이 아닌 특정 시간 뒤에 실행하거나 주기적으로 실행해야 하는 경우에 사용되는 함수
  • console
    - 개발 시 디버깅을 위해 사용하는 객체로 변수의 값을 확인할 때 주로 사용

2. console 객체

- 개발 시 디버깅을 위해 사용하는 객체로 변수의 값을 확인할 때 주로 사용

console.log() 평범한 로그를 콘솔에 표시
console.log(내용, 내용, ....) 처럼 여러 내용을 동시에 표시 가능
console.error() 에러를 콘솔에 표시, 일반적으로 log()와 동일
console.table() 배열의 요소로 객체 리터널을 넣으면, 속성들이 테이블 형식으로 표현
console.dir() 객체를 콘솔에 표시할 때 사용
console.time() console.timeEnd(레이블)과 대등되어 같은 레이블을 가진 time과 timeEnd 사이의 시간을 측정

console 객체 예시(모듈을 이용해 생성)

const ConsoleExam = {
    time: () => {
        console.log("\n\n\n ===========================> time")
        console.log("측정시간")
        
        console.time("timecheck")       // 시작 시간, 시작 끝 사이 코드 걸리는 시간
        for(let i = 0; i < 5; i++) {
            console.log('timecheck ----- ' + i)
        }
        console.timeEnd("timecheck")    // 끝나는 시간(시작과 끝의 이름을 맞춰줘야 함)
        
        global.console.log("측정종료")
    },

    table: () => {
        console.log("\n\n\n ===========================> table")
        
        const jsonarray = [
            {name: "홍길동", birth: 1997, gender: "남", age: 21, time: {time: 1}},
            {name: "김유신", birth: 1998, gender: "남"},
            {name: "유관순", birth: 1999, gender: "여"},
            {name: "김철수", birth: 1992, gender: "남"},
            {name: "김영희", birth: 1993, gender: "여"}
        ]
        
        console.table(jsonarray)
        // console.dir(jsonarray)
    },

    log: () => {
        console.log("\n\n\n ===========================> log")

        console.log("console.log를 사용한 array 객체 출력")
        console.log(["apple", "banana", "orange"])
        console.log("\n")

        console.log("console.log를 사용해 json 객체를 출력")
        console.log({name: "홍길동", title: "test-file", age: 10})

        console.log("console.log를 사용해 여러개의 인자를 출력")
        console.log("test", [1,2,3], {title:"test"}, [{name: "홍길동"}, {name: "김유신"}])
    },

    dir: () => {
        console.log("\n\n\n ===========================> dir")

        console.dir("console.dir를 사용한 array 객체 출력")
        console.dir(["apple", "banana", "orange"])
        console.log("\n")

        console.dir("console.dir를 사용해 json 객체를 출력")
        console.dir({name: "홍길동", title: "test-file", age: 10})

        console.dir("console.dir를 사용해 여러개의 인자를 출력")
        console.dir("test", [1,2,3], {title:"test"}, [{name: "홍길동"}, {name: "김유신"}])
    
        const obj = {
            outside: {
                inside: {
                    key: "value",
                    test: {name: "test"}
                }
            }
        }

        console.dir("depth는 객체 안의 객체를 몇 단계까지 보여줄지를 결정, 기본값 : 2")
        console.dir(obj)
        // console.dir(객체, 옵션)
        console.dir(obj, {colors: false, depth: 2})
        console.dir(obj, {colors: false, depth: 1})
        console.dir(obj, {colors: false, depth: 3})
        console.dir(obj, {colors: false, depth: 10})
    },

    rest: () => {
        console.log("\n\n\n ===========================> rest")

        // 콘솔에서는 의미가 없지만 웹에서는 차이가 남
        console.log("기본")
        console.info("정보")
        console.debug("디버그")
        console.warn("경고")
        console.error("에러")

        try{
            test
        } catch {
            console.trace("에러위치추적")
        }
    }
}

module.exports = ConsoleExam

예시 결과

===========================> time
측정시간
timecheck ----- 0
timecheck ----- 1
timecheck ----- 2
timecheck ----- 3
timecheck ----- 4
timecheck: 0.819ms
측정종료

 ===========================> table
┌─────────┬──────────┬───────┬────────┬─────┬─────────────┐
│ (index) │   name   │ birth │ gender │ age │    time     │
├─────────┼──────────┼───────┼────────┼─────┼─────────────┤
│    0    │ '홍길동' │ 1997  │  '남'  │ 21  │ { time: 1 } │
│    1    │ '김유신' │ 1998  │  '남'  │     │             │
│    2    │ '유관순' │ 1999  │  '여'  │     │             │
│    3    │ '김철수' │ 1992  │  '남'  │     │             │
│    4    │ '김영희' │ 1993  │  '여'  │     │             │
└─────────┴──────────┴───────┴────────┴─────┴─────────────┘

 ===========================> log
console.log를 사용한 array 객체 출력
[ 'apple', 'banana', 'orange' ]


console.log를 사용해 json 객체를 출력
{ name: '홍길동', title: 'test-file', age: 10 }
console.log를 사용해 여러개의 인자를 출력
test [ 1, 2, 3 ] { title: 'test' } [ { name: '홍길동' }, { name: '김유신' } ]

 ===========================> dir
'console.dir를 사용한 array 객체 출력'
[ 'apple', 'banana', 'orange' ]


'console.dir를 사용해 json 객체를 출력'
{ name: '홍길동', title: 'test-file', age: 10 }
'console.dir를 사용해 여러개의 인자를 출력'
'test'
'depth는 객체 안의 객체를 몇 단계까지 보여줄지를 결정, 기본값 : 2'
{ outside: { inside: { key: 'value', test: [Object] } } }
{ outside: { inside: { key: 'value', test: [Object] } } }
{ outside: { inside: [Object] } }
{
  outside: { inside: { key: 'value', test: { name: 'test' } } }
}
{
  outside: { inside: { key: 'value', test: { name: 'test' } } }
}

 ===========================> rest
기본
정보
디버그
경고
에러
Trace: 에러위치추적
    at Object.rest (C:\1900_frontend_LSJ\workspace\myserver\src\Day05\consoleExam.js:89:21)
    at Object.<anonymous> (C:\1900_frontend_LSJ\workspace\myserver\server.js:94:13)
    at Module._compile (node:internal/modules/cjs/loader:1155:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
    at Module.load (node:internal/modules/cjs/loader:1033:32)
    at Function.Module._load (node:internal/modules/cjs/loader:868:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:22:47

3. timer 객체

타이머 객체 생성
setTimeout(콜백 함수, 밀리초) 주어진 밀리초(1000분의 1초) 이후에 콜백 함수를 실행
setInterval(콜백 함수, 밀리초) 주어진 밀리초마다 콜백 함수를 반복 실행
타이머 삭제
clearTimeout(아이디) setTimeout 취소
clearInterval(아이디) setInterval 취소
  • 삭제를 위한 아이디(변수)에 할당
    const timeout = setInterval(() => {
           console.log('1초마다 출력')
    }, 1000);

    // 10초 후에 제거
    clearInterval(timeout)
const TimerExam = {
    timeout: () => {
        setTimeout(() => {
            console.log("1.5초 후에 실행됩니다.")
        }, 1500)
    },

    interval: () => {
        setInterval(() => {
            console.log("1초 마다 실행됩니다.")
        }, 1000)
    },

    clear: () => {
        const timer1 = setTimeout(() => {
            console.log("3초 후에 실행됩니다.")
        }, 3000)

        const timer2 = setInterval(() => {
            console.log("1초마다 실행되는 인터벌....")
        }, 1000)

        // 2초후에 실행될 타이머
        setTimeout(() => {
            console.log("2.5초 후에 실행되는 타이머 클리어")

            // 첫번째 타이머 setTimeout 삭제
            clearTimeout(timer1);

            // 두번째 타이머 setInterval를 삭제
            clearInterval(timer2);
        }, 2500)
    },

    counter: () => {

        let count = 1;

        // 10까지만 카운팅할 타이머를 생성하자...
        const timer = setInterval(() => {
            console.log("타이머 =====> " + count)
            count++;
            if(count > 10) {
                clearInterval(timer)
            }
        }, 1000)
    },

    // 문제 10 ~ 1까지 카운트하는 다운 카운트를 만드세요
    downcounter: () => {
        var count = 10;

        const downtimer = setInterval(() =>{
            console.log("다운타이머 ====> " + count)
            count--;
            if(count < 0) {
                clearInterval(downtimer)
            }
        }, 1000)
    }
}

module.exports = TimerExam

 

반응형