본문 바로가기

JavaScript

You Don't Know Node / translate

[번역하기]

 

나는 compiled languages를 싫어한다.

사실, 한가지만 싫어한다. 자바만 !

내 목표는 세상을 더 좋은 곳으로 만드는 것이다.

 

내 계획.

Software helps people

소프트웨어는 사람들을 돕는다.

+

Node is a good tool to build good software

노드는 소프트웨어를 만들기 좋은 도구다.

+

I need to teach as many people Node as posiible

최대한 많은 사람에게 노드를 가르쳐야 한다.

 

내 목표(이번 글에서)

당신이 core Node에 흥미를 가지게 할거다.

 

밑바닥부터 시작하자 : 왜 노드를 이용하지?

입력/출력은 가장 비용이 큰 작업 중 하나다. (CPU)

노드는 non-blocking I/O를 가지고 있다.

너무 복잡해 !
IO call이 끝나지 않았을 때도 다른 작업을 허용한다.

 

Java Sleep

System.out.println("Step: 1");
System.out.println("Step: 2");
Thread.sleep(1000);
System.out.println("Step: 3");

Node "Sleep" / Process Multiple Tasks

console.log('Step: 1')
setTimeout(function () {
	console.log('Step: 3')
}, 1000)
console.log('Step: 2')

Blocking Web Server

Non-Blocking Web Server

위 방식(non-blocking)은 일반적 OS 스레드의 흐름과 대조된다.

스레드 기반의 네트워킹은 상대적으로 비효율적이고 사용하기 어렵다.

더 나아가 노드 유저들은 dead-locking을 걱정할 필요가 없어진다.

 

멀티스레딩을 잘못사용하면 모든걸 망칠 수 있다.

Blocking 시스템은 반드시 멀티스레드여야 한다.

다행히 노드는 single 스레드다.

아직도 node.js에서 blocking 방식으로 이용할 수 있긴하다.

//blocking.js
console.log('Step: 1')
for (var i =1; i<1000000000; i++) {
	// This will take 100-1000ms
}
console.log('Step: 2')

아래 두 코드를 비교해보길 바란다.

Blocking Node.js Code

var fs = require('fs')

var contents = fs.readFileSync('accounts.txt','utf8')
console.log(contents)
console.log('Hello Ruby\n')

var contents = fs.readFileSync('ips.txt','utf8')
console.log(contents)
console.log('Hello Node!')
//accounts.txt->Hello Ruby->ips.txt->Hello Node!

Non-Blocking Node.js Code

var fs = require('fs')

fs.readFile('accounts.txt','utf8', function(error, contents){
   console.log(contents)
})
console.log('Hello Ruby\n')

fs.readFile('ips.txt','utf8', function(error, contents){
   console.log(contents)
})
console.log('Hello Node!')
//Hello Ruby->Hello Node->... accounts.txt->ips.txt or ips.txt->accounts.txt

 

Node는 다른 플렛폼보다 훨씬 빠르다.

얼마나 많은 사람들이 블로킹 I/O 시스템으로 만들어진 어플리케이션에서 퍼포먼스의 끝까지 도달했을지 생각해봐라

아마 많지 않을 거다.

내가 Node를 제일 좋아하는 이유

JavaScript가 모든 곳에 있다. 한 언어가 모든 것을 한다.

한 언어가 모든 곳에서 이용되면.

1. 더욱 빠르게 생각할수 있다.

2. 코드를 재사용가능성 up

3. 빨리 배운다.

 

Node !== Browser JavaScript

 

Node Core Modules

누가 콜백을 좋아하고 이해하니?

fs.readdir(source, function (err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function (filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function (err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function (width, widthIndex) {
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})

콜백만을 이용해서 큰 설계는 하기 매우 힘들다.

 

Events 이벤트

Events == Node Observer Pattern

- Subject

- Observers (event listeners) on a subject

- Event triggers

이벤트는 단순히 한 문장과 그에 반응하는 callback이라고 묘사할수 있다.

이벤트

var events = require('events')
var emitter = new events.EventEmitter();

이벤트

emitter.on('done', function(results) {
  console.log('Done: ', results)
})

이벤트 에미터 사용하기

var events = require('events')
var emitter = new events.EventEmitter();

emitter.on('knock', function() {
	console.log('Who\'s there?');
})

emitter.on('knock', function() {
	console.log('Go away!')
})

emitter.emit('knock')

 

크기가 큰 데이터에 관한 문제들

Streams 를 이용하면 된다.

streams: 데이터 묶음을 위한 추상화

스트림을 이용하면 전체 소스를 가져올때까지 기다릴 필요가 없다.

스트림엔 4가지 종류가 있다.

- Readable

- Writable

- Duplex

- Transform

 

 

앗, 너무 띄엄띄엄 문장이 있는 글. 프레젠테이션을 번역하고 있었다.

그만하고 디테일한 글을 봐야겠다.

'JavaScript' 카테고리의 다른 글

node / express 공부기.  (0) 2020.04.25
JS 배열 정리하고 가기.  (0) 2020.04.24
JS 문자열 메서드 훑고 가기.  (0) 2020.04.24
var / let / const 간단정리  (0) 2020.04.22
closure  (0) 2020.04.22