Node.js

오픈소스 비즈니스 컨설팅
Pnuskgh (토론 | 기여)님의 2018년 9월 24일 (월) 19:11 판 (→‎Express)
둘러보기로 가기 검색하러 가기

Server Side JavaScript인 Node.js를 정리 합니다.

Node.js 개요

Node.js는 서버사이드 자바스크립트이며 Google의 자바스크립트 엔진인 V8이 빌트인되어 있습니다. Event 기반이며 non-blocking I/O를 지원합니다. 자바스크립트의 표준라이브러리 프로젝트인 CommonJS의모듈시스템을 지원합니다.

  • Event loop 방식
  • 동작 요청시 동작이 완료될 경우에 실행될 Call Back을 지정하는 방식

Node.js 설치

CentOS에서 설치

yum install nodejs npm

Windows에서 설치

다운로드 사이트에서 node-v0.12.0-x64.msi 파일을 다운로드 하여 설치 합니다.

Node.js 문법

Node.js 기초

내장 상수

내장 함수와 특수 함수

상수/변수 선언

객체 선언

Module 선언

별도의 파일에 생성할 모듈을 위한 코드를 작성 한다. 작성한 코드를 modules.exports(={}) 객체에 할당하면 다른 프로그램에서 호출하여 사용할 수 있다.

모듈을 불러쓰는 프로그램

"use strict";

var myModule=require("myModule.js");

모듈을 작성한 프로그램 (myModule.js)

#--- module.exports와 exports는 같은 것이다.
module.exports = {
    #--- 여기에 코드를 기술 한다.
}
exports.~ = { ~ }                                            #--- 개발 코드를 등록 한다.

연산자

조건문/반복문

오류 처리

try {

} catch(error) {
}

기타 문법

Type 변환

입출력

전역 변수

  • 전역 객체 : global
  • process.env : 애플리케이션 실행 환경
  • process.version : node.js 버전
  • process.arch : CPU 정보
  • process.platform : Platform 정보
  • process.argv : 실행 명령 파라미터
  • Event 전역 객체
  • process.exit : 애플리케이션 종료 이벤트
  • process.beforeExit : 애플리케이션이 종료 되기 전에 발생하는 이벤트
  • process.uncaughtException : 예외 처리되지 않은 이벤트
  • 전역 함수
  • process.exit : 애플리케이션 종료
  • process.nextTick : 이벤트 루프내 동작을 모두 실행한 후 콜백 실행
  • setTimeout : 동작 지연
  • setEnterval : 동작 반복
  • clearTimeout
  • console.log(~), console.info(~), console.warn(~), console.error(~)
  • console.time(TIMER_NAME), console.timeEnd(TIMER_NAME)
global.console.log(~)
console.log(~)                                         //--- global은 생략 가능

브라우저 입출력

Cookie 입출력

세션 입출력

데이터베이스 입출력

파일 입출력

//--- __dirname : 현재 폴더
//--- __filename : 현재 파일명
var pathUtil = require('path');
var path = __dirname + pathUtil.sep + 'logo.png';
pathUtil.join(~, ~);

path = pathUtil.normalize(path);
// path.basename();
// path.dirname();
// path.extname();
var info = path.parse(~);

var fs = require('fs');
fs.access(~, mode, callback)      //--- fs.F_OK, fs.R_OK, fs.W_OK, fs.X_OK
fs.accessSync(~, mode)

fs.stat(~, callback);
fs.statSync(~);

var fd = fs.openSync(~, 'rwa);
fs.closeSync(fd);

fs.open(~, 'rwa', function(error, fd) { ~ });
fs.close(fs, callback);

fs.unlink(~);
fs.rename(~, ~, callback);
fs.renameSync(~, ~)

fs.readdir(~, callback)
fs.readdirSync(~)
fs.mkdir(~, callback)
fs.rmdir(~, callback)
fs.mkdirSync(~)
fs.rmdirSync(~)

동기식

var fs = require('fs');
var content = fs.readFileSync("readme.txt", "utf8");

console.log(content);

fs.writeFileSync(~, ~)

비동기식

var fs = require('fs');
fs.readFile("readme.txt", "utf9", function(error, content) {
  if (error) {
    console.log("Error");
    return;
  }
  console.log(content);
});

fs.writeFile(~, ~, callback);

이메일 입출력

Command Line 입출력

유용한 Node.js 모듈

Util

var util = require('util');

util.format(~);
util.inherits(자식, 부모);                           //--- 상속

EventEmitter

emitter.addListener(event, listener)
emitter.on(event, function(error, result) { ~ })
emitter.once(event, listener)                        //--- 한번만 실행
emitter.removeListener(event, listener)
emitter.removeAllListeners([event])
emitter.setMaxListeners(n)                           //--- 이벤트 핸들러 최대 갯수 지정
emitter.emit(event, ...)                             //--- 이벤트를 강제로 발생

var customEvent = new event.EventEmitter();
customEvent.on(~, ~);

Express

웹 어플리케이션을 만들기 위한 framework 이다.

Debug

https://www.npmjs.com/package/debug

$env:DEBUG_COLORS='no'
$env:DEBUG_DEPTH=10 
$env:DEBUG_SHOW_HIDDEN='enabled'

$env:DEBUG='*'

Console

node 명령을 사용하여 node Console을 실행할 수 있습니다.

종료시에는 process.exit(0); 또는 Ctrl_C + Ctrl_C를 눌러 줍니다.

Package 관리

modbus 폴더를 만들고 jsmodbus 모듈을 설치 한다.

mkdir -p /work/appl/modbus
cd /work/appl/modbus
npm init
   #--- scada_modbus, 0.0.1, Modbus for SCADA, scada.js, 엔터, 엔터, 엔터, OBCon, 엔터, yes
   This utility will walk you through creating a package.json file.
   It only covers the most common items, and tries to guess sensible defaults.

   See `npm help json` for definitive documentation on these fields
   and exactly what they do.

   Use `npm install <pkg> --save` afterwards to install a package and
   save it as a dependency in the package.json file.

   Press ^C at any time to quit.
   name: (modbus) scada_modbus
   version: (1.0.0) 0.0.1
   description: Modbus for SCADA
   entry point: (index.js) scada.js
   test command:
   git repository:
   keywords:
   author: OBCon
   license: (ISC)
   About to write to /work/appl/modbus/package.json:

   {
     "name": "scada_modbus",
     "version": "0.0.1",
     "description": "Modbus for SCADA",
     "main": "scada.js",
     "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1"
     },
     "author": "OBCon",
     "license": "ISC"
   }
   Is this ok? (yes) yes

# npm install [모듈명] --save                                  #--- 모듈 설치후 package.json 파일에 추가
npm install jsmodbus --save                                  #--- 3.1.0
npm install -g mocha                                         #--- 5.2.0
npm install -g    sinon                                      #--- 6.3.3

npm 주요 명령

npm init : 패키지 관리 설정 파일인 package.json 파일을 생성 한다.
npm install [모듈명] --save : 모듈을 설치하고 package.json 파일에 반영 한다.
npm install [모듈명] --save-dev : 모듈을 설치하고 package.json 파일의 개발용 모듈에 반영 한다.
npm install : package.json 파일을 참조하여 필요한 모듈을 설치 한다.
npm install -g 전역 설치 : CLI로 사용
# npm init                                                  #--- 패키지 관리 설정 파일인 package.json 파일을 생성 한다.
# npm install jsmodbus --save                               #--- jsmodbus 3.1.0 설치
vi  package.json
   {
     "name": "scada_modbus",
     "version": "0.0.1",
     "keywords": [
       "SCADA",
       "Modbus"
     ],
     "description": "Modbus for SCADA",
     "main": "scada.js",
     "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1"
     },
     "author": "OBCon Inc.",
     "license": "Copyright OBCon Inc. All right reserved.",
     "dependencies": {
       "jsmodbus": "^3.1.0"
     },
     "devDependencies": {}
   }
npm install                                             #--- package.json 파일로 설치를 시작 한다.
npm update

npm install -g mocha                                    #--- mocha 5.2.0 전역 설치
npm install -g sinon                                    #--- sinon 6.3.3 전역 설치

npm list                                                #--- 설치된 모듈 목록 조회
npm list -g --depth=0                                   #--- 전역 설치된 모듈 목록 조회

npm uninstall ~ 
npm uninstall ~ --save|--save-dev

npm version major                                       #--- Major 버전을 올립니다.
npm version minor                                       #--- Minor 버전을 올립니다.
npm version patch                                       #--- Patch 버전을 올립니다.

참고 문헌

Test Framework

테스트 방식

  • TDD (Test-Driven Development) : 테스트 자체에 집중
  • BDD (Behaviour-Driven Development) : 비즈니스 요구 사항에 집중


Karma 모듈을 설치 합니다.

  • 설정 파일 : karma.conf.js, test-main.js
  • 테스트 모듈 실행 : karma start karma-conf.js

npm install karma-cli -g
npm install karma -g --save-dev
npm install karma-coverage --save-dev
npm install karma-jasmine --save-dev
# npm install karma-chrome-launcher --save-dev
karma --version

karma init karma.conf.js
# Which testing framework do you want to use ? jasmine
# Do you want to use Require.js ? yes
# Do you want to capture any browsers automatically ? Chrome
# What is the location of your source and test files ?
# Should any of the files included by the previous patterns be excluded ?
# Do you wanna generate a bootstrap file for RequireJS? yes
# Do you want Karma to watch all the files and run the tests on change ? yes

환경 변수 설정 : CHROME_BIN = chrome.exe


Jasmine 모듈을 설치 합니다.

  • 설정 파일 : spec/support/jasmine.json
  • 테스트 모듈 실행 
    • js/sample.js, test/sampleSpec.js
    • 모든 Test 프로그램은 ~Spec.js 형태로 작성하여야 합니다.
    • jasmine-node --test-dir test --color --verbose
    • jasmine-node --test-dir test --autotest --watch test --color

npm install jasmine -g
jasmine init

npm install jasmine-node -g
jasmine-node --version


참고 문헌

참고 문헌