NodeJS

[basic] Node.js - URL Module (주소 처리 모듈)

1,457
목차
  1. url 모듈
  2. Node.js 파일 서버

 

url 모듈

[정의]

 

1. URL 주소를 읽을 수 있는 부분부분으로 분할.

2. url.parse() 메서드 이용. 더 자세히 보기.

 


[구문]

 

var url = require('url');

 


[예제] 

 

var url = require('url'); // 모듈 사용.

var adr = 'http://localhost:8080/index.php?open=2012&site=homzzang.com';


var hz = url.parse(adr, true); // 구문 분석 후, 객체 반환.


console.log(hz.host); // 반환: 'localhost:8080'

console.log(hz.pathname); // 반환: '/index.php'

console.log(hz.search); // 반환: '?open=2012&site=homzzang.com'


var hzinfo = hz.query; // 반환 : { open: 2012, site: 'homzzang.com' }

console.log(hzinfo.site); //반환 : 'homzzang'

 


PS. 

※ console.log() 이용해서, cmd 모드에 출력됨. 

※ 브라우저에 출력시키려면, http 모듈을 사용. (아래 예제 참고)

 

Node.js 파일 서버

 

http, url, fs 모듈을 이용해, 접속 URL 감지해 다른 내용 뿌리기. 

 


1-1. C:\User\사용자명\boy.html 파일 생성.

※ 도메인/boy.html 접속 시, 출력할 내용.

 

<!DOCTYPE html>

<html>

<body>

<h1>Boy</h1>

<p>I'm a boy.</p>

</body>

</html>

 

1-1. C:\User\사용자명\girl.html 파일 생성.

※ 도메인/girl.html 접속 시 출력할 내용.

 

<!DOCTYPE html>

<html>

<body>

<h1>Girl</h1>

<p>I'm a girl.</p>

</body>

</html>

 

2. C:\User\사용자명\hz.js 생성.

※ http, url, fs 모듈 사용한, Node.js 서버 역할.

 

var http = require('http');

var url = require('url');

var fs = require('fs');


http.createServer(function (req, res) {

  var q = url.parse(req.url, true);

  var filename = "." + q.pathname;

  fs.readFile(filename, function(err, data) {

    if (err) {

      res.writeHead(404, {'Content-Type': 'text/html'});

      return res.end("404 Not Found");

    } 

    res.writeHead(200, {'Content-Type': 'text/html'});

    res.write(data);

    return res.end();

  });

}).listen(8080);

 

3. 

아래 명령어로 생성한 Node.js 파일 시작 설정.

C:\User\사용자명>node hz.js

 

4.

아래 주소로 각각 접속해 출력 결과 확인.

 

http://localhost:8080/boy.html

결과값:

Boy

I'm a boy. 

 

 

http://localhost:8080/girl.html

결과값:

Girl

I'm a girl. 

 



분류 제목
basic Node.js - Home
basic Node.js - Intro (소개)
basic Node.js - Start (시작) - 사용 환경 구축
basic Node.js - Modules (모듈)
basic Node.js - HTTP Module (데이터 전송 모듈)
basic Node.js - File System Module (파일 시스템 모듈)
basic Node.js - URL Module (주소 처리 모듈)
basic Node.js - NPM (노드 패키지 관리자)
basic Node.js - Events (이벤트)
basic Node.js - Upload Files (파일 업로드) 2
basic Node.js - Email (이메일 보내기)
mysql Node.js - MySQL 설치・연결 + 쿼리 보내기
mysql Node.js - MySQL Create Database (DB 생성)
mysql Node.js - MySQL Create Table (테이블 생성) ※ Primary key 설정.
mysql Node.js - MySQL Insert Into (데이터 삽입)
1/5
목록
 홈  PC버전 로그인 일본어
웹디자인언어 1
서버관리언어
고급코딩언어
그누보드
제작의뢰
Q&A
커뮤니티 3
웹유틸
회원센터
홈짱 PC버전 로그인