Node js

KimJS·2020년 4월 24일
0

REPL

  • 자바스크립트는 스크립트 언어이므로 미리 컴파일을 하지 않아도 즉석에서 코드를 실행할 수 있다.
  • 노드는 입력한 코드를 읽고(Read), 해석하고(Eval), 결과물을 반환하고(Print), 종료할 때까지 반복(Loop)한다고 해서 REPL(Read Eval Print Loop)이라고 부른다.
> const str ='Hello world, hello node';
undefined
> console.log(str);
Hello world, hello node
Undefined
>
  • REPL은 한두 줄짜리 코드를 테스트해보는 용도로는 좋지만 여러 줄의 코드를 실행하기에는 불편하다.
  • 긴 코드는 코드를 자바스크립트 파일로 만든 후, 파일을 통째로 실행하는 것이 좋다.

JS파일 실행

  • 사용하는 js파일 만들기
function helloWorld() {
  console.log('Hello World');
  helloNode();
}
function helloNode() {
  console.log('Hello Node');
}
helloWorld();
  • js파일 실행
$ node helloWorld
Hello World
Hello Node

모듈로 만들기

  • 노드는 코드를 모듈로 만들 수 있다는 점에서 브라우저의 자바스크립트와는 다르다.
  • 모듈이란 특정한 기능을 하는 함수나 변수들의 집합이다.
  • 자체로도 하나의 프로그램이면서 다른 프로그램의 부품으로도 사용할 수 있다.
  • 모듈로 만들어두면 여러 프로그램에 해당 모듈을 재사용할 수 있다. 자바스크립트에서 코드를 재사용하기 위해 함수로 만드는 것과 비슷하다.
  • 모듈 작성
const odd ='홀수입니다';
const even ='짝수입니다';

module.exports = {
  odd,
  even,
};
  • 모듈 사용
const { odd, even } = require('./var');

function checkOddOrEven(num) {
  if (num % 2) { // 홀수면
    return odd;
  }
  return even;
}

module.exports = checkOddOrEven;
  • require 함수 안에 불러올 모듈의 경로를 적어준다.
  • 다른 폴더에 있는 파일도 모듈로 사용할 수 있으며,require 함수의 인자로 제공하는 경로만 잘 지정해주면 된다.(파일 경로에서 js나 json 같은 확장자는 생략가능)

여러개의 모듈 사용

const { odd, even } = require('./var');
const checkNumber = require('./func');

function checkStringOddOrEven(str) {
  if (str.length % 2) { // 홀수면
    return odd;
  }
  return even;
}

console.log(checkNumber(10));
console.log(checkStringOddOrEven('hello'));
  • 모듈 하나가 여러 개의 모듈을 사용할 수 있다.
  • 모듈 하나가 여러 개의 모듈에 사용될 수도 있다.

1개의 댓글

comment-user-thumbnail
2020년 4월 27일

ㄷㄷ

답글 달기