>npm install express 

>npm install routes

>npm install jade


1. app.js

/*
    폴더 구조
    1. /node_modules - nodejs module이 설치될 공간
    2. /public - connect 모듈의 Static 미들웨어를 사용하여 웹 서버에 올라가는 폴더
                 (js, css, images등 리소스 생성)
    3. /routes - 페이지 라우트와 관련된 모듈 (index.js)
    4. /views - EJS, Jade 파일과 같은 템플릿 파일
 
    express 프레임워크 설정
    1. basepath - 기본 URL 지정
    2. views - 뷰 폴더 지정
    3. view engine - 뷰 엔진 지정
    4. view option - 뷰 엔진 옵션 지정
    5. view cache - 뷰 캐시를 사용할지 지정
    6. case sensitive routes - 페이지 라우트를 할 때 대소문자를 구분할지 지정
    7. stric routing - 엄격 경로 확정을 사용할지 지정
*/
 
//Module
var express = require('express'),
    routes = require('./routes');
var app = module.exports = express();
 
//Configuration
app.configure(function(){
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});
 
// 실행 환경 설정
app.configure('development', function(){
    app.use(express.errorHandler({dumpExceptions:true, showStack:true}));
});
 
app.configure('production', function(){
    app.use(express.errorHandler());   
});
 
//Routes
// GET - /
app.get('/', routes.index);
app.get('/redirect', routes.redirect);
app.get('/product', routes.product);
app.get('/product/insert', routes.product.insert);
app.get('/product/edit', routes.product.edit);
 
app.listen(3000);


2. /routes/index.js

/* get hompage */
exports.index = function (req, res){
    res.render('index', {title:'Express'});
}
 
exports.life = function(req, res){
    res.writeHead(200, {'Content-Type':'text/html'});
    res.end('

Life Page

'); } exports.redirect = function(req, res){ //페이지 강제 이동 //res.writeHead(302, {'Location' : 'http://applenamu3.blog.me'}); //res.end(); res.redirect('http://applenamu3.blog.me'); } // GET - /product exports.product = function(req, res){ res.render("product", { title : 'Product Page' }); } // GET - /product/insert exports.product.insert = function(req, res){ res.render("product/insert",{ title:'Insert Page' }); } // GET - /product/edit exports.product.edit = function(req, res){ res.render('product/edit', { title:'Edit Page' }); }


3. /views/index.jade, /views/product/index.jade, insert.jade, edit.jade

h1= title
p Node.js Programing for Modern Web Development
hr


'프로그래밍 > nodeJS' 카테고리의 다른 글

[nodeJS] Socket.IO 방만들기  (0) 2015.01.27
[nodeJS] Socket.IO 모듈  (0) 2015.01.27
[nodeJS] connect / connect_router 모듈  (0) 2015.01.27
[nodeJS] jade 모듈  (0) 2015.01.27
[nodeJS] ejs 모듈  (0) 2015.01.27
Posted by august5pm
,

>npm install connect 

>npm install connect_router


1. server.js

/*
__filename : 현재 실행 중인 코드의 파일 경로
__dirname : 현재 실행중인 코드의 폴더 경로
*/
 
// http 서비스를 하기 위해
var connect = require("connect"),
    connect_router = require("connect_router"),
    fs = require("fs"),
    url = require("url");
 
//서버 객체를 얻어옵니다.
var server = connect.createServer()
.use(connect.static(__dirname + "/Resource")) // 각종 리소스 폴더
.use(connect.bodyParser()) // post 방식 전송된 데이터 읽어오기 위해
.use(connect_router(main)) // 페이지 라우팅 처리할 함수
.use(connect.errorHandler({stack:true, message:true, dump:true})) // 에러출력 및 처리
.listen(3000);
 
//페이지 라우팅을 해서 클라이언트에 서비스할 함수
function main(app){
    app.get("/", function(request, response){
        console.log("index.html 클라이언트의 요청이 왔습니다.");
        //클라이언트에 응답할 html 파일을 읽어서 응답한다.
        fs.readFile("html/index.html", function(error, data){
            response.writeHead(200, {"Content-Type":"text/html"});
            response.end(data);
        });
    });
   
    app.get("/login.html", function(request, response){
        console.log("login.html 클라이언트의 요청이 왔습니다.");
        //클라이언트에 응답할 html 파일을 읽어서 응답한다.
        fs.readFile("html/login.html", function(error, data){
            response.writeHead(200, {"Content-Type":"text/html"});
            response.end(data);
        });
    });
   
    // get 방식으로 form 전송 햇을때
    app.get("/login", function(request, response){
        console.log("get / memIn.html 클라이언트의 요청이 왔습니다.");
        // 클라이언트가 전송한 값을 읽어온다.
        var query = url.parse(request.url, true).query;
        // 읽어온값 확인 해보기
        console.log(query);
        // 페이지 강제이동
        response.writeHead(302, {"Location":"/member/memIn.html"});
        response.end();
    });
   
    // post 방식으로 form 전송햇을때
    app.post("/login", function(request, response){
        console.log("post / memIn.html 클라이언트의 요청이 왔습니다.");
        // body 부분에 붙어서 오는 데이터를 읽어오기 위해.
        var body = request.body;
        console.log(body.id + " / " + body.pwd);
        // 페이지 강제이동
        response.writeHead(302, {"Location":"/member/memIn.html"});
        response.end();
    });
   
    app.get("/member/memIn.html", function(request, response){
        console.log("클라이언트의 요청이 왔습니다.");
        //클라이언트에 응답할 html 파일을 읽어서 응답한다.
        fs.readFile("html/member/memIn.html", function(error, data){
            response.writeHead(200, {"Content-Type":"text/html"});
            response.end(data);
        });
    });
}


2. /html/index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>connect / router module(index.html)</title>
</head>
<body>
<h1>index.html 페이지 입니다.</h1>
<ul>
    <li><a href="login.html">로그인</a></li>
    <li><a href="member/memIn.html">회원가입</a></li>
</ul>
</body>
</html>


3. /html/login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>connect / router module(login.html)</title>
</head>
<body>
<form action="login" method="post">
    아이디<input type="text" name="id"/><br/>
    비밀번호<input type="text" name="pwd"/><br/>
    <input type="submit" value="로그인"/>
</form>
</body>
</html>


4. /html/member/memIn.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>connect / router module(memberIn.html)</title>
</head>
<body>
<h1>회원 가입 페이지 입니다.</h1>
</body>
</html>
</html> 

'프로그래밍 > nodeJS' 카테고리의 다른 글

[nodeJS] Socket.IO 모듈  (0) 2015.01.27
[nodeJS] Express / Routes / Jade 모듈  (0) 2015.01.27
[nodeJS] jade 모듈  (0) 2015.01.27
[nodeJS] ejs 모듈  (0) 2015.01.27
[nodeJS] http 모듈 + FileSystem 모듈  (0) 2014.12.29
Posted by august5pm
,

>npm install jade


1. server.js

//모듈 추출
var http = require('http');
var jade = require('jade');
var fs = require('fs');
 
//서버를 생성하고 실행
http.createServer(function(request, response){
    //jade 파일 읽기
    fs.readFile('index.jade', 'utf8', function(error, data){
        // jade 모듈 사용
        var fn = jade.compile(data);
 
        // 출력
        response.writeHead(200, {'Content-Type':'text/html'});
        response.end(fn());
    });
}).listen(3000, function(){
    console.log('Server Running at http:127.0.0.1:3000');
});


2. index.jade

html
    head
        title Jade Example
    body
        h1 Hello Jade
        p Node.js & Jade
        hr
        a(href="http://august5pm.tistory.com", target="_blank") Go To Link

'프로그래밍 > nodeJS' 카테고리의 다른 글

[nodeJS] Express / Routes / Jade 모듈  (0) 2015.01.27
[nodeJS] connect / connect_router 모듈  (0) 2015.01.27
[nodeJS] ejs 모듈  (0) 2015.01.27
[nodeJS] http 모듈 + FileSystem 모듈  (0) 2014.12.29
[nodeJS] hello world  (0) 2014.12.29
Posted by august5pm
,

> npm install ejs


1. server.js

//모듈 추출
var http = require('http');
var fs = require('fs');
var ejs = require('ejs');
 
//서버 생성 및 실행
http.createServer(function(request, response){
    // EJSPage.js 파일 로드
    fs.readFile('index.ejs', 'utf8', function(error, data){
        response.writeHead(200, {'Content-Type':'text/html'});
        response.end(ejs.render(data, {
                title:'EJS Example',
                sub:'Multiplication'
        }));
    });
}).listen(3000, function(){
    console.log('Server Running at http://127.0.0.1:3000');
});


2. index.ejs

<% var num = 2 %>
<h1><%= title %></h1>
<h2><%= sub  %> x <%= num %></h2>
<% for(var i=1; i<10; i++) { %>
    <p><%= num %> X <%= i %> = <%= num* i %><p>
<% } %>

'프로그래밍 > nodeJS' 카테고리의 다른 글

[nodeJS] connect / connect_router 모듈  (0) 2015.01.27
[nodeJS] jade 모듈  (0) 2015.01.27
[nodeJS] http 모듈 + FileSystem 모듈  (0) 2014.12.29
[nodeJS] hello world  (0) 2014.12.29
[nodeJS] nodeJS 란?  (0) 2014.12.29
Posted by august5pm
,

1.server.js

// 모듈 추가
var fs = require('fs');
var http = require('http');
 
// 서버 실행
http.createServer(function(request, response){
    //html 파일 읽기
    fs.readFile('index.html', function(error, data){
            response.writeHead(200, {'Content-Type' : 'text/html'});
            response.end(data);
    });
}).listen(3000, function(){
    console.log('Server Running at http:// 127.0.0.1:3000');
});


2. index.html

  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>http and FileSystem</TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
 
<BODY>
<h1>Hello Node.js</h1>
</BODY>
</HTML>

'프로그래밍 > nodeJS' 카테고리의 다른 글

[nodeJS] jade 모듈  (0) 2015.01.27
[nodeJS] ejs 모듈  (0) 2015.01.27
[nodeJS] hello world  (0) 2014.12.29
[nodeJS] nodeJS 란?  (0) 2014.12.29
[nodeJS] nodeJS 설치하기(윈도우용-ver 0.10.34 기준)  (0) 2014.12.28
Posted by august5pm
,

Node.js의 설치가 제대로 되었는지 확인하기 위해서 hello world를 만들어 보겠습니다.

 

1. 콘솔창에 hello world  출력하기

 

Node.js 를 실행하고자 하는 폴더에 node.basic.js라는 파일을 생성하고 아래와 같이 코드를 입력 합니다.


console.log('hello, world');


그리고 콘솔창(명령프롬프트)을 실행시켜 줍니다. 실행시키는 방법에는 두가지가 있습니다.

 

첫째, 윈도우 시작 > 실행 > cmd 를 치고 엔터


 


둘째, 윈도우 시작 > 모든 프로그램 > 보조 프로그램 > 명령 프롬프트 클릭  


 

 

콘솔창을 실행했다면 자신이 만든 js파일이 있는 폴더로 이동합니다. 콘솔창에서는 이동을 할때 cd 라는 명령어를 사용합니다.

ex) c드라이브로 이동할 경우 - cd c:\

 

저는 C:\nodejs\exp\001_hello_world 폴더에 js 파일이 있기 때문에 해당 폴더로 이동하겠습니다.

직접 경로를 쳐서 이동하는 방법도 있지만 경로가 복잡하거나 길 경우에는 경로를 복사하여 이동 할 수도 있습니다.

 

아래와 같이 해당 폴더의 경로를 선택후 마우스 오른쪽 버튼을 눌러서 복사를 선택합니다.


 



콘솔창으로 이동하여 마우스 오른쪽 버튼을 누르고 붙여넣기를 선택합니다.


 

js파일이 있는 폴더로 이동했다면

> node node.basic.js

를 입력하고 엔터를 누릅니다. 제대로 실행되고 있다면 콘솔창에 아래와 같이 hello,world라고 출력 됩니다.



2. 서버를 실행하고 웹브라우저에서 hello world 출력하기

node.server.js 파일을 생성하고 아래와 같이 코드를 입력합니다.


// 모듈 추출
var http = require('http');
 
// 웹 서버를 생성 및 실행
http.createServer(function (request, response){
    response.writeHead(200, {'Content-Type':'text/html'});
    response.end('

Hello World

'); }).listen(3000, function(){ console.log('server running at http://localhost:3000'); });



node.server.js 파일을 실행시킵니다.

> node node.server.js

 

콘솔 창에 아래와 같이 보인다면 성공~



웹 브라우저를 열고 http://127.0.0.1:3000 을 입력합니다. 그럼 아래와 같이 Hello World라는 큼지막한 글씨가 짜잔~^-^


'프로그래밍 > nodeJS' 카테고리의 다른 글

[nodeJS] jade 모듈  (0) 2015.01.27
[nodeJS] ejs 모듈  (0) 2015.01.27
[nodeJS] http 모듈 + FileSystem 모듈  (0) 2014.12.29
[nodeJS] nodeJS 란?  (0) 2014.12.29
[nodeJS] nodeJS 설치하기(윈도우용-ver 0.10.34 기준)  (0) 2014.12.28
Posted by august5pm
,

nodeJS는 2009년 라이언 달(RyanDahl)이 개발한 서버개발 환경이며 대규모 네트워크 애플리케이션을 개발하고자 만들어졌습니다.

 

아래 영상은 개발자 라이언 달(RyanDahl)의 Node.js에 대한 소개 영상입니다.




1. 기존의 네트워크 프로그래밍과 nodeJS의 차이점 

 

1) 기존의 네트워크 프로그래밍은 스레드 기반의 동기방식

처리량이 많아지면 스레드를 늘려서 동시에 일처리 하기 때문에 많은 양의 일을 처리에 대한 좋은 해결방법이지만 스레드를 여러 개 만들어 동시에 처리해야하기 때문에 메모리리 사용량이 많다.

 

2) nodeJS는 이벤트 기반의 비동기 방식 (Single thread / Event loop)

스레드는 한개만 생성하며 이벤트 사용으로써 빠른 일처리를 합니다. 처리량이 많더라도 스레드가 한개이기 때문에 메모리 사용량과 같은 시스템 리소스 사용량에는 거의 변화가 없다.

 

 

2. nodeJS의 장단점 

 

1) 장점

 

- 웹개발자들 대부분이 사용할 수 있는 자바스크립트 언어기반으로 기존 웹 개발자들의 접근이 용이하다.

- Google에서 V8 자바스크립트 엔진의 속도를 지속적으로 향상시키고 있는만큼 V8엔진을 사용하는 Node.js의 속도도 계속 향상 될 것.

- C++을 사용하여 기능확장이 용이하다.

 

 

2) 단점

 

- V8 자바스크립트 엔진이 아무리 빨라도 C언어 또는 C++ 언어로 개발된 서버보다는 느리다.

- 1.0 버전 조차 공개되지 못한 신생 개발환경이다. (포스팅 기준 - 버전 0.10.34)

- 많은 개발자들이 동기처리 방식에 익숙해 져있기때문에 비동기 처리 하려면 무엇을 바꿔야 할지에 대한 혼란이 올 수 있다.

- 동기 처리구조의 코드는 일 처리의 순서대로 적은 코드 이기 때문에 직관적이지만 비동기 처리구조의 코드는 결과처리에 대한 코드가

  언제 호출 될지 알 수 없다.

'프로그래밍 > nodeJS' 카테고리의 다른 글

[nodeJS] jade 모듈  (0) 2015.01.27
[nodeJS] ejs 모듈  (0) 2015.01.27
[nodeJS] http 모듈 + FileSystem 모듈  (0) 2014.12.29
[nodeJS] hello world  (0) 2014.12.29
[nodeJS] nodeJS 설치하기(윈도우용-ver 0.10.34 기준)  (0) 2014.12.28
Posted by august5pm
,




Node.js를 처음 알게 되었을 때만해도 윈도우용이 없어서 리눅스 환경을 위해 cygwin을 설치하고 매우 복잡했던 것으로 기억이 되는데0.6.3 버전 부터 윈도우에서도 Node.js가 가진 모든 기능을 정상적으로 사용할 수 있게 되면서 부터 설치방법은 간단해졌습니다.

 

사실 Next 버튼만 누르면 설치가 되기 때문에 설치 포스트 자체가 의미가 없다는 생각이 들었지만 정리를 시작한다는 기분으로 설치부터 포스팅 하였습니다.

 

Node.js 다운로드 : http://www.nodejs.org/




<이미지 1-1> nodeJS 사이트에 접속하여 DOWNLOAD를 클릭합니다.





<이미지 1-2> 사용자의 운영체제에 맞는 파일을 다운로드 합니다.




<이미지 1-3> 설치파일을 실행시키고 Next 버튼을 클릭




<이미지 1-4> 라이센스 동의에 체크하고 Next 버튼을 눌러줍니다




<이미지 1-5> 설치할 폴더를 지정하고 Next 버튼을 눌러줍니다.




<이미지 1-6> 선택적으로 설치하고 싶은 것만 지정할 수 있지만 저는 그냥 기본으로하고 Next를 눌렀습니다. 




<이미지 1-7> 이제 드디어 인스톨 버튼이 보이네요~ 인스톨 버튼을 눌러줍니다.




<이미지 1-8> 앞에서 선택한 내용들을 바탕으로 설치가 시작됩니다.




<이미지 1-9> 드디어 설치 완료~




<이미지 1-10> 설치가 잘 되었나 시작에서 cmd를 실행시키고 npm을 쳐봤는데 에러가 발생하네요.





<이미지 1-11> nodeJS가 설치된 폴더에서 node_modeules 폴더로 들어가면 npm폴더가 있습니다. npm폴더를 복사합니다.




<이미지 1-12> C:\Users\컴퓨터이름\AppData\Roaming 에 <이미지 1-11>에서 복사한 npm폴더를 붙여넣기 합니다.


(AppData 폴더가 보이지 않는 분은 경로창 아래 구성 버튼을 누르고 폴더 및 검색 옵션에서 보기 탭을 클릭한 후 숨김 파일, 폴더 및 드라이브 표시에 체크해 주셔야 합니다.)




<이미지 1-13> 다시 cmd창에서 npm을 입력하고 엔터를 눌러봅니다.




<이미지 1-14> 아까와 다르게 npm 명령어들에 대한 설명이 나옵니다. 성공~^-^



설치 후에 cmd창에서 npm을 입력하고 엔터를 눌렀을 때 오류가 발생하여 전역변수 설정을 확인해보니 패스가  C:\Users\컴퓨터이름\AppData\Roaming 로 잡혀 있었습니다. 해당 폴더 안에는 npm 폴더가 없더군요. 제가 설치를 하면서 무엇을 빼먹은건지 ㅡ_ㅡ;  npm폴더를 찾아서 복사해 넣는걸로 완료 되었으나, 원인을 한번 찾아봐야겠네요.



'프로그래밍 > nodeJS' 카테고리의 다른 글

[nodeJS] jade 모듈  (0) 2015.01.27
[nodeJS] ejs 모듈  (0) 2015.01.27
[nodeJS] http 모듈 + FileSystem 모듈  (0) 2014.12.29
[nodeJS] hello world  (0) 2014.12.29
[nodeJS] nodeJS 란?  (0) 2014.12.29
Posted by august5pm
,
document.write(window.location.hash);
document.write(window.location.pathname);
document.write(window.location.hostname);
document.write(window.location.href);



예제 도메인) http://www.example.com:8080/search?q=devmo#test



1. Properties


 Property

 Description 

 Example 

 hash

 주소값에 붙어있는 anchor값 반환

 #test

 host

 URL의 도메인과 포트 반환

 www.example.com:8080

 hostname

 URL의 도메인 반환

 www.example.com

 href

 URL 반환

 http://www.example.com:8080/search?q=devmo#test

 origin

 프로토콜 + URL의 도메인 + 포트

 http://www.example.com:8080

 pathname

 URL 경로 반환

 /search

 port

 서버포트 반환

 8080

 protocol

 프로토콜 반환

 http:

 search

 URL에 붙은 매개변수 반환(물음표 뒤의 값)

 ?q=devmo



2. Methods


 Method

 Description 

 assign(url)

 새로운 주소 이동

 reload(forceget)

 현재 페이지 새로고침

 replace(url)

 새로운 주소 이동 (세션 히스토리가 남지 않기 때문에 back 버튼으로 이동 불가) 



예제 1) 새 페이지로 이동하기


window.location.assign("http://www.example.com"); // or
window.location = "http://www.example.com";



예제 2) 현재 페이지 새로고침


window.location.reload(true);



예제 3) replace()를 사용하여 새 페이지로 이동하기


function reloadPageWithHash() {
  var initialPage = window.location.pathname;
  window.location.replace('http://example.com/#' + initialPage);
}


'프로그래밍 > javascript' 카테고리의 다른 글

[javascript] 10의 자리 체크  (0) 2016.11.17
[javascript] 1차 방정식  (0) 2016.11.17
[javascript] 1차 함수  (0) 2016.11.17
[javascript] HTML 에서 파라미터 가져오기  (0) 2015.02.03
[javascript] D-Day 구하기  (0) 2015.01.28
Posted by august5pm
,
var img = $("").attr('src', 'http://somedomain.com/image.jpg')
    .load(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) 
        {
            alert('broken image!');
        } 
        else 
        {
            $("#something").append(img);
        }
    });

'프로그래밍 > jQuery' 카테고리의 다른 글

셀렉트 박스 초기화 시키기  (0) 2016.10.19
Posted by august5pm
,