Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

NodeJS - 기초 본문

NodeJS

NodeJS - 기초

보람- 2023. 8. 25. 15:03

목차

1. NodeJS 정의

2. NodeJS 내장기능

3. global

4. "REPL"

5. 모듈 Module

6. process


 

 

 

1. NodeJS 정의

- 공식문서에 따르면 V8 javascript엔진을 기반으로 구축된 javascript 런타임이라고한다.

- 내 컴퓨터에 있는 자원을 사용하기 위해서 (파일조작이 가능한지)

- 브라우저 런타임은 파일을 읽고 쓰는 능력이 없어서 파일입출력이 안되는데 nodejs는 파일입출력이 가능하다.

  → 그래서 서버도 만들수있다.

 

 

2. NodeJS 내장 기능

- this (global)
- Module 모듈
- process
- os
- path
- url , querystring
- fs

 

 


3. global

- 브라우저에서 this는 전역객체가 window가 나오고

- NodeJS에서 this하면 전역객체가 global이 나온다.

→ localtion.herf, document.querySelector 등 익숙하게 사용했던 window객체들을 NodeJS에서 사용X

<ref *1> Object [global] {
  global: [Circular *1],
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  structuredClone: [Function: structuredClone],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  atob: [Function: atob],
  btoa: [Function: btoa],
  performance: Performance {
    nodeTiming: PerformanceNodeTiming {
      name: 'node',
      entryType: 'node',
      startTime: 0,
      duration: 50.35470000002533,
      nodeStart: 1.6211000001057982,
      v8Start: 3.775499999523163,
      bootstrapComplete: 27.741100000217557,
      environment: 10.384499999694526,
      loopStart: -1,
      loopExit: -1,
      idleTime: 0
    },
    timeOrigin: 1692928259736.035
  },
  fetch: [AsyncFunction: fetch]
}

 

 

 

4. REPL


R : Read (읽고)
E : Evaluate (평가하고)
P : Print (출력하고)
L : Loop (반복하고)


*** 001.js 파일 실행하기

cd nodejs
ls
node 001.js

- 001.js 파일을 읽고 평가하고 실행되고 끝이난다.

- 그런데 작업할때 여러 파일을 쪼개서 사용하니까 모듈이 필요하다.





5. 모듈(Module)

- 하나의 프로세스안에서 다른 파일을 실행해서 결과물을 가져와 사용할수있는것!

   → 내가 실행한 파일만 실행된다!

- NodeJS에는 commonjs 모듈 시스템이있다!
   

★ commonjs keyword
module.exports
require(파일이름)

 

 

모듈활용예시 ① 숫자를 넣을 때

// 001.js 파일

const a = require("./002.js");
const blockX = 10;

console.log(blockX + a);
// 002.js 파일

const a = 10;
console.log(a);
module.exports = a;

- 001.js 파일을 실행하는 명령을 했고, 파일을 읽어내려가는중에 require(./002.js) 를 보고 002.js 평가를 한다.

- a에 10을 할당하고 console 10을 출력하고, a을 내보내서 가져온다.

- 그래서 blockX+a (10+10) 계산된 20이 출력된다.

 

 

모듈활용예시 ② 객체에 함수값을 넣을 때

// 003.js 파일

exports.sum1 = (a, b) => a + b;
exports.sum10 = (a) => a + 10;
// 004.js 파일

const a = require("./003"); // {}

console.log(a); // {a:10, sum1:function, sum10:function}

const b = a.sum10(10);
console.log(b); // 20

 

 

모듈활용예시 실수로 module 입력하지못했을때

// 005.js 파일
const b = 10;
// 006.js 파일
const a = require("./005");
console.log(a);

빈 객체가 나온다 {}

 

 

6. process 라는 내장객체

console.log(process.version); // v18.17.1
console.log(process.arch); //x64
console.log(process.platform); // linux
console.log(process.pid); // process id 2092

 

리눅스에서 작업관리자 보기

ps -ef

ps -ef | grep node

sudo kill -9 [pid입력]
# 프로세스 끄는것

node process.js &
# 다시 실행시키는 방법

setInterval(() => {
  console.log("실행되나?", process.pid);
}, 1000);

 


 

※ NodeJS 목표!!

- 웹서버를 만들수있는 사람
- 데이터베이스를 이해할수있는 사람
- 네트워크를 어느정도 이해되는 사람

 

※ NodeJS 공식문서 참고하기 ( commonjs 모듈시스템 )

https://nodejs.org/dist/latest-v18.x/docs/api/modules.html

 

※ 터미널에서 node 입력하면 들어가지고 ctrl C 두번 누르면 나가진다!

 

※ 순환참조라고해서 무한루프가 되는 말이 안되는 코드를 적었을경우 NodeJS가 한번 실행한 결과물을 메모리에 저장해두었다가 보여준다고한다! 나중에 언제 이슈가 생길지 모르니까 사용하지 않기로

// a.js 파일


const b = require("./b.js");
console.log(b);
module.exports = { name: "boram" };
// b.js 파일

const a = require("./a.js");
console.log(a);
module.exports = { name: "guniee" };

원래라면 에러가 나야하는데 일단 결과물을 보여준다.

※ 리눅스용어는 외우기!

 

※ foreground,background

- 내가 보고있을때만 실행하는건 foreground

- 내가 안보고있을때 실행하는건 background

라고 이해해두기!!!