"Node.js"의 두 판 사이의 차이

오픈소스 비즈니스 컨설팅
둘러보기로 가기 검색하러 가기
60번째 줄: 60번째 줄:
  
 
=== 파일 입출력 ===
 
=== 파일 입출력 ===
 +
 +
동기식
 +
var fs = require('fs');
 +
var content = fs.readFileSync("readme.txt", "utf8");
 +
 +
console.log(content);
 +
 +
비동기식
 +
var fs = require('fs');
 +
fs.readFile("readme.txt", "utf9", function(error, content) {
 +
  if (error) {
 +
    console.log("Error");
 +
    return;
 +
  }
 +
  console.log(content);
 +
});
  
 
=== 이메일 입출력 ===
 
=== 이메일 입출력 ===

2018년 9월 18일 (화) 15:38 판

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 기초

내장 상수

내장 함수와 특수 함수

상수/변수 선언

객체 선언

연산자

조건문/반복문

오류 처리

기타 문법

Type 변환

입출력

전역 변수

브라우저 입출력

Cookie 입출력

세션 입출력

데이터베이스 입출력

파일 입출력

동기식

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

console.log(content);

비동기식

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

이메일 입출력

Command Line 입출력

유용한 Node.js 모듈

Express

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

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


참고 문헌

참고 문헌