2015년 4월 19일 일요일

Mac, Node.js 학습 3일차] 기본 내장 모듈

1. Node.js에 대한 기본 API 정보
  - http://nodejs.org/api/

 2. os 모듈
  - 운영체제 관련 정보에 관한 기본적인 기능을 제공하는 모듈
  - 제공 메소드
     . hostname() : Host Name
     . type() : OS 이름
     . platform() : OS Platform
     . uptime() : OS가 실행된 시간
     . totlamem() : 시스템 총 사용 메모리
     . freemem() : 시스템의 가용 메모리
     . cpus() : CPU 정보
     . 그외 tempdir(), endianness() 등의 정보 제공
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat module.os.js
// OS 모듈을 활성화
var os = require('os');

// 모듈 사용
console.log(os.hostname());
console.log(os.type());
console.log(os.uptime());
console.log(os.totalmem());
console.log(os.freemem());

baesunghan:~/Documents/workspace/nodejs$node module.os.js
Tovensui-MacBook-Pro.local
Darwin
4233
8589934592
518901760
baesunghan:~/Documents/workspace/nodejs$


3. url 모듈
  - url을 호출하고 Parsing 하는 모듈
  - 제공 메소드
    . parse : Url 문자열을 URL 객체로 변환해 리턴
    . format : URL 객체를 URL 문자열로 변환해 리턴
    . resolve : 매개변수를 조합하여 완전한 Url 문자열을 생성해 리턴
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat module.url.js
// 모듈 객체 생성
var url = require('url');

// 모듈 사용
var parsedObj = url.parse('http://www.wingkostory.com//news/view.do?news_category_no=1&news_no=6685');
console.log(parsedObj);

baesunghan:~/Documents/workspace/nodejs$node module.url.js
{ protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.wingkostory.com',
  port: null,
  hostname: 'www.wingkostory.com',
  hash: null,
  search: '?news_category_no=1&news_no=6685',
  query: 'news_category_no=1&news_no=6685',
  pathname: '//news/view.do',
  path: '//news/view.do?news_category_no=1&news_no=6685',
  href: 'http://www.wingkostory.com//news/view.do?news_category_no=1&news_no=6685' }
baesunghan:~/Documents/workspace/nodejs$


4. Query String 모듈
  - url 에서 사용되는 query를 객체로 변환하거나 객체를 스트링으로 변환하는 모듈
  - url 객체의 query 부분을 만들어 준다.
  - 제공 Method
    . stringigy() : 쿼리 객체(JSON : {'id':'bsh', 'name':'Toven'})를 쿼리 문자열(id=bsh&name=Toven)로 변환
    . parse() : 쿼리 문자열을 쿼리 객체(JSON)로 변환
  - 사용 예
    var qs = require('query string');
    var param = qs.parse('id=bsh&name=Toven');
    console.log(param.id);
    console.log(param.name);
    var str = qs.stringify(param);
    console.log(str);

5. util 모듈
  - Utility성 기능을 모아둔 모듈
  - 제공 Method
    . format : 매개변수로 입력된 값을 조합해 리턴
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat module.util.js
// 객체 생성
var util = require('util');

// 모듈 사용
var data = util.format('%d + %d = %d', 54, 100, 123);
console.log(data);

baesunghan:~/Documents/workspace/nodejs$node module.util.js
54 + 100 = 123
baesunghan:~/Documents/workspace/nodejs$


6. File System 모듈
  - 파일 입출력과 관련된 모듈
  - 유용한 제공 Method
    . readFile(file, encoding, callback) : 파일을 비동기로 읽음, 비동기로 처리 후 callback 함수가 수행됨
    . readFileSync(file, encoding) : 파일을 동기로 읽음
    . writeFile(file, data, encoding, callback) : 파일을 비동기로 기록, 비동기로 처리 후 callback 함수가 수행됨
    . writeFileSync(file, data, encoding) : 파일을 동기로 기록
   - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat module.fs.js
// 파일 객체 생성
var fs = require('fs');

// 파일 객체 read 모듈 사용
fs.readFile('testfile.txt', 'UTF-8', function(error, data) {
console.log('Read Async Completed!!!');
console.log(data);
});

var text = fs.readFileSync('testfile.txt', 'UTF-8');
console.log('Read Sync Complete!!!');
console.log(text);

var data = 'Hello World!!!!';

fs.writeFile('testfile2.text', data, 'UTF-8', function(error) {
console.log('Write Async Completed!!!');
});

fs.writeFileSync('testfile3.text', data, 'UTF-8');
console.log('Write Sync Completed!!');

baesunghan:~/Documents/workspace/nodejs$
baesunghan:~/Documents/workspace/nodejs$node module.fs.js
Read Sync Complete!!!
This is a testfile.txt
이것은 테ㅡ트 파일입니다.

Write Sync Completed!!
Write Async Completed!!!
Read Async Completed!!!
This is a testfile.txt
이것은 테ㅡ트 파일입니다.

baesunghan:~/Documents/workspace/nodejs$ls -al
total 104
drwxr-xr-x  15 baesunghan  staff  510  4 19 18:53 .
drwxr-xr-x  14 baesunghan  staff  476  4 11 21:36 ..
-rw-r--r--   1 baesunghan  staff  180  4 14 01:17 main.js
-rw-r--r--   1 baesunghan  staff  556  4 19 18:52 module.fs.js
-rw-r--r--   1 baesunghan  staff  226  4 14 01:18 module.js
-rw-r--r--   1 baesunghan  staff  202  4 17 15:55 module.os.js
-rw-r--r--   1 baesunghan  staff  196  4 17 16:10 module.url.js
-rw-r--r--   1 baesunghan  staff  137  4 17 18:19 module.util.js
-rw-r--r--   1 baesunghan  staff   30  4 14 00:53 node.basic.js
-rw-r--r--   1 baesunghan  staff  370  4 14 00:53 node.global.js
-rw-r--r--   1 baesunghan  staff  555  4 14 01:09 node.process.js
-rw-r--r--   1 baesunghan  staff  346  4 11 21:52 node.server.js
-rw-r--r--   1 baesunghan  staff   60  4 19 18:27 testfile.txt
-rw-r--r--   1 baesunghan  staff   15  4 19 18:53 testfile2.text
-rw-r--r--   1 baesunghan  staff   15  4 19 18:53 testfile3.text
baesunghan:~/Documents/workspace/nodejs$cat testfile3.text
Hello World!!!!baesunghan:~/Documents/workspace/nodejs$


    => readFileAsync, writeFileAsync는 Asyc로 동작하므로 Sync로 동작하는 readFile, writeFile과 동작 순서가 다름을 볼수 있다.

  - 예외처리 : file 처리 모듈은 반드시  예외처리를 해야함. readFileSync, writeFileSync모듈은 try ~ catch로 처리하고, readFile, writeFile의 Async Method는 callback 함수의 error 파라메타를 이용해서 처리함.
baesunghan:~/Documents/workspace/nodejs$cat module.fsex.js
// 파일 객체 생성
var fs = require('fs');

// 파일 객체 read 모듈 사용
fs.readFile('testfile.txt', 'UTF-8', function(error, data) {
console.log('Read Async Completed!!!');
if (error) {
console.log(error);
} else {
console.log(data);
}
});

try {
var text = fs.readFileSync('testfile.txt', 'UTF-8');
console.log('Read Sync Complete!!!');
console.log(text);
} catch(e) {
console.log(e);
}

var data = 'Hello World!!!!';

fs.writeFile('testfile2.text', data, 'UTF-8', function(error) {
console.log('Write Async Completed!!!');
if (error) {
console.log(error);
} else {
console.log(data);
}
});

try {
fs.writeFileSync('testfile3.text', data, 'UTF-8');
console.log('Write Sync Completed!!');
} catch (e) {
console.log(e);
}

baesunghan:~/Documents/workspace/nodejs$



댓글 없음:

댓글 쓰기