Node.js

설치!


# 주석: `#`으로 시작하는 명령은 bash에서 무시됩니다.
# 아래 명령을 한 줄씩 차례대로 입력하세요
$ nvm install 8.11.1
$ nvm use 8.11.1
$ nvm alias default 8.11.1 # nvm-windows는 필요없음
        

Node.js REPL


$ node
        

// 한 줄 짜리 코드 입력하기
> 'hello node'
'hello node'

// 위쪽 화살표 키를 입력해서 이전 명령 불러오기
> 'hello node'
'hello node'

> const factorial = n => n < 1 ? 1 : n * factorial(n-1)
undefined

> factorial(3)
6
        

// 여러 줄에 나눠서 입력하기
> function factorial2(n) {
... return n < 1 ? 1 : n * factorial(n-1)
... }
undefined

> factorial2(4)
24

// `.exit`를 입력하거나 `Ctrl+C`를 두 번 입력해서 나가기
> .exit
        

// Node.js module 사용하기
> const os = require('os') // 급할땐 `os = ...`
undefined

> os.platform()
'linux'

> os.freemem()
658300928
        

Node.js로 파일 실행시키기


$ node (파일 경로)
        

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Node.js Module


// name.js

// `module.exports`에 저장한 값은 다른 모듈에서 불러올 수 있음
module.exports = {
  familyName: '김',
  givenName: '승하',
  fullName: function() {
    return this.familyName + this.givenName
  }
}
        

// calc.js

// `exports`로도 참조 가능
exports.add = (x, y) => x + y
exports.sub = (x, y) => x - y
        

REPL에서 불러오기


// Node.js 내장 모듈과는 다르게 경로를 지정해야 함
> const name = require('./name')
undefined
> name
{ familyName: '김',
  givenName: '승하',
  fullName: [Function: fullName] }
> name.familyName
'김'
> name.fullName()
'김승하'
> require('./calc').add(1, 2)
3
        

NPM

Node.js 패키지 관리 도구 + 클라우드 패키지 저장소

  • 의존 패키지 관리
  • 스크립트 실행
  • 패키지 설정
  • NPM에 패키지 배포
  • Node.js 종합 작업 도구

Hello NPM


$ mkdir hello-npm
$ cd hello-npm
$ npm init -y
$ code .
        

// package.json
{
  "name": "hello-npm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
        

package.json

패키지 정보를 담고 있는 파일

dependencies
`npm install --save` 명령으로 설치한 패키지가 기록됨
scripts
원래 목적은 패키지 생명주기마다 자동으로 실행되는 명령을 등록하기 위함이나, 개발자 편의를 위해 자주 사용되는 명령을 등록하는 용도로 더 많이 사용됨

$ npm install --save randomstring # node_modules에 저장됨
        

// index.js
const randomstring = require('randomstring')
console.log(randomstring.generate())
        

// package.json
...
  "scripts": {
    "start": "node index.js"
  }
...
        

$ npm start