# 주석: `#`으로 시작하는 명령은 bash에서 무시됩니다.
# 아래 명령을 한 줄씩 차례대로 입력하세요
$ nvm install 8.4
$ nvm use 8.4
$ nvm alias default 8.4 # nvm-windows는 필요없음
$ 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 (파일 경로)
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.
프로그램의 흐름이
외부 요인에 의해 일어나는 사건에 의해
결정되는 프로그래밍 양식
약속된 방식으로 이벤트 핸들러를 작성함으로써
외부 이벤트가 일어났을 때 코드를 실행
// DOM 이벤트 핸들러 등록 (웹 브라우저)
domElement.addEventListener('click', function(e) {
e.stopPropagation()
alert('hello')
})
// 서버도 똑같이 합니다.
// (단, 프레임워크를 쓸 때는 직접 이벤트를 다룰 일이 별로 없음)
// HTTP 응답 이벤트 핸들러 등록 (Node.js)
httpResponse.on('data', data => {
console.log(data)
})
Blocking I/O는 스레드가 입력/출력이 완료될 때까지 기다렸다가 다음 코드를 실행
Non-blocking I/O는 스레드가 입력/출력을 기다리지 않고 코드를 계속 실행
I/O 성능 향상 & 복잡한 코드
// 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
// Node.js 내장 모듈과는 다르게 경로를 지정해야 함
> const name = require('./name')
undefined
> name
{ familyName: '김',
givenName: '승하',
fullName: [Function: fullName] }
> name.familyName
'김'
> name.fullName()
'김승하'
> require('./calc').add(1, 2)
3
Node.js 패키지 관리 도구 + 클라우드 패키지 저장소
$ 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"
}
패키지 정보를 담고 있는 파일
$ 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