1. view (pc)- flash actionscirpt3 starling framwork

2. control (mobile) - html5 device orientation event

3. server (node.js) - socket.io

 

flash를 view로 사용하였고, flash의 object를 모바일기기로 컨트롤하며, 그 둘을 Node.js의 소켓으로 연결하는 테스를 해 보았습니다. 모바일 기기의 좌, 우 기울어짐에 따라 flash의 object가 움직이고 있으며, 모바일 쪽에는 시작하기 버튼을 두어 게임에 관련된 전반적인 사항들을 모두 모바일로 제어 할 수 있도록 설계하였습니다.

 

테스트 모바일 디바이스로는 아이패드, 아이폰, 갤럭시s2를 사용하였으며, pc와 통신에 있어서 만족할 만한 반응속도를 얻을 수 있었습니다. 영상에서 사용된 디바이스는 갤럭시s2 입니다.

Posted by august5pm
,

1. app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// --------------------------------------
// Imports
// --------------------------------------
var net = require('net');
var mySocket;
  
// --------------------------------------
// Construct The Socket
// --------------------------------------
// create the server and register event listeners
var server = net.createServer(function(socket) {
    mySocket = socket;
    mySocket.on("connect", onConnect);
    mySocket.on("data", onData);
});
  
// --------------------------------------
// Events
// --------------------------------------
/**
 * Handles the Event: <code>"connect"</code>.
 *
*/
function onConnect()
{
    console.log("Connected to Flash");
}
  
/**
 * Handles the Event: <code>"data"</code>.
 *
 * When flash sends us data, this method will handle it
 *
*/
function onData(d)
{
    if(d == "exit\0")
    {
        console.log("exit");
        mySocket.end();
        server.close();
    }
    else
    {
        console.log("From Flash = " + d);
        mySocket.write(d, 'utf8');
    }
}
  
// --------------------------------------
// Start the Socket
// --------------------------------------
server.listen(3000, "127.0.0.1");


2. flash (as3)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package
{
  
    // --------------------------------------
    // Imports
    // --------------------------------------
    import flash.display.Sprite;
    import flash.events.DataEvent;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;
    import flash.net.XMLSocket;
    import flash.text.TextField;
    import flash.ui.Keyboard;
  
    // --------------------------------------
    // Class
    // --------------------------------------
    /**
    * <p>The <code>NodeJSDemo</code> class is ...</p>
    *
    */
    public class NodeJSDemo extends Sprite
    {
  
        // --------------------------------------
        // Properties
        // --------------------------------------
        // PUBLIC GETTER/SETTERS
        /**
         * The core object which connects client to
         *  server for real-time communication
         */
        private var _xmlSocket:XMLSocket;
  
        /**
         * The sole UI element to show some test output
         */
        private var _textField:TextField;
  
        // PUBLIC CONST
  
        // PRIVATE
  
        // --------------------------------------
        // Constructor
        // --------------------------------------
        /**
         * This is the constructor.
         *
         */
        public function NodeJSDemo()
        {
            // SUPER
            super();
  
            // EVENTS
            addEventListener(Event.ADDED_TO_STAGE, _onAddedToStage);
  
            // VARIABLES
  
            // PROPERTIES
            _textField = new TextField ();
            _textField.width = 300;
            _textField.height = 300;
            _textField.multiline = true;
            _textField.htmlText = "";
            addChild(_textField);
  
            // METHODS
  
        }
  
        // --------------------------------------
        // Methods
        // --------------------------------------
        // PUBLIC
        /**
         * Handles the Event: <code>Event.CHANGE</code>.
         *
         * @param aEvent <code>Event</code> The incoming aEvent payload.
         *
         * @return void
         *
         */
        private function _onAddedToStage(aEvent : Event):void
        {
            //  CREATE THE SOCKET AND CONNECT - I'M NOT SURE WHAT PARAMETERS ARE VALID HERE
            //  BUT IT MUST MATCH THE SETTINGS WITHIN THE 'HelloWorldNodeJS.js' FILE YOU ARE USING
            _xmlSocket = new XMLSocket("127.0.0.1", 3000);
  
            // EVENTS
            stage.removeEventListener(MouseEvent.CLICK,         _onAddedToStage);
            //
            _xmlSocket.addEventListener(Event.CONNECT,          _onConnected);
            _xmlSocket.addEventListener(IOErrorEvent.IO_ERROR,  _onIOError);
  
        }
  
        // PRIVATE
  
        // --------------------------------------
        // Event Handlers
        // --------------------------------------
        /**
         * Handles the Event: <code>Event.CHANGE</code>.
         *
         * @param aEvent <code>Event</code> The incoming aEvent payload.
         *
         * @return void
         *
         */
        private function _onConnected(aEvent : Event):void
        {
            //  TRACE
            trace("onConnect() aEvent: " + aEvent);
  
            //  EVENTS
            _xmlSocket.removeEventListener(Event.CONNECT,           _onConnected);
            _xmlSocket.removeEventListener(IOErrorEvent.IO_ERROR,   _onIOError);
            //
            _xmlSocket.addEventListener(DataEvent.DATA,             _onDataReceived);
            _xmlSocket.addEventListener(Event.CLOSE,                _onSocketClose);
            //
            stage.addEventListener(KeyboardEvent.KEY_UP,            _onKeyUp);
  
        }
  
        /**
         * Handles the Event: <code>Event.CHANGE</code>.
         *
         * @param aEvent <code>Event</code> The incoming aEvent payload.
         *
         * @return void
         *
         */
        private function _onSocketClose(aEvent : Event):void
        {
            //  TRACE
            trace("_onSocketClose aEvent : " + aEvent);
  
            //  EVENTS
            stage.removeEventListener(KeyboardEvent.KEY_UP, _onKeyUp);
            _xmlSocket.removeEventListener(Event.CLOSE, _onSocketClose);
            _xmlSocket.removeEventListener(DataEvent.DATA, _onDataReceived);
        }
  
        /**
         * Handles the Event: <code>KeyboardEvent.KEY_UP</code>.
         *
         * @param aEvent <code>KeyboardEvent</code> The incoming aEvent payload.
         *
         * @return void
         *
         */
        private function _onKeyUp(evt:KeyboardEvent):void
        {
            //  HANDLE KEYS
            if (evt.keyCode == Keyboard.ESCAPE) {
                //1. SEND 'KILL THE SERVER' TO THE SERVER
                _xmlSocket.send("exit");
            }
            else {
                //2. SEND ANY NON-ESCAPE KEY'S CODE ('38' FOR EXAMPLE) TO SERVER
                //      THIS IS A SILLY EXAMPLE OF SENDING A NUMBER TO THE SERVER
                //      JUST SO THE SERVER CAN SEND IT BACK. SIMPLE.
                _xmlSocket.send(evt.keyCode);
            }
        }
  
        /**
         * Handles the Event: <code>DataEvent.DATA</code>.
         *
         * @param aEvent <code>DataEvent</code> The incoming aEvent payload.
         *
         * @return void
         *
         */
        private function _onDataReceived(aEvent : DataEvent):void
        {
            try {
  
                //  Show the server data in text
                _textField.htmlText += ("From Server: " + aEvent.data + "n");
  
                //scroll down to show latest line
                _textField.scrollV = _textField.maxScrollV;
  
            } catch (error : Error) {
                //  TRACE
                trace("_onDataReceived error:  " + error);
            }
        }
  
        /**
         * Handles the Event: <code>IOErrorEvent.IO_ERROR</code>.
         *
         * @param aEvent <code>IOErrorEvent</code> The incoming aEvent payload.
         *
         * @return void
         *
         */
        private function _onIOError(aEvent : IOErrorEvent):void
        {
            //  TRACE
            trace("_onIOError aEvent: " + aEvent);
  
            //  EVENTS
            _xmlSocket.removeEventListener(Event.CONNECT, _onConnected);
            _xmlSocket.removeEventListener(IOErrorEvent.IO_ERROR, _onIOError);
            stage.addEventListener(MouseEvent.CLICK, _onAddedToStage);
        }
  
    }
}


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

[nodeJS] Flash + Html5 + Node.js  (0) 2015.01.27
[nodeJS] Socket.IO 방만들기  (0) 2015.01.27
[nodeJS] Socket.IO 모듈  (0) 2015.01.27
[nodeJS] Express / Routes / Jade 모듈  (0) 2015.01.27
[nodeJS] connect / connect_router 모듈  (0) 2015.01.27
Posted by august5pm
,

>npm install socket.io 


1. server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// fs 모듈
var fs = require('fs');
  
// 서버생성
var server = require('http').createServer();
var io = require('socket.io').listen(server);
  
// 서버실행
server.listen(3000, function(){
    console.log('Server Running at http:127.0.0.1:3000');
});
  
// 웹 서버 이벤트 연결
server.on('request', function(request, response){
    //html 파일 읽기
    fs.readFile('index.html', function(error, data){
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end(data);
    });
});
  
  
// 소켓서버 이벤트 연결
io.sockets.on('connection', function(socket){
    // join 이벤트
    socket.on('join', function(data){
        socket.join(data);
        socket.set('room', data);
    });
    
    // message 이벤트
    socket.on('message', function(data){
        socket.get('room', function(error, room){
            io.sockets.in(room).emit('message', data);
        });
    });
});


2. index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE HTML>
<html>
 <head>
  <title> SOCKET.IO ROOM </title>
  <meta charset="utf8" />
  <script src="/socket.io/socket.io.js"></script>
  <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
  <script>
    $(document).ready(function(){
        //변수선언
        var room = prompt('방 이름을 입력하세요.','');
        var socket = io.connect();
  
        //소켓 이벤트 연결
        socket.emit('join', room);
        socket.on('message', function(data){
            $('<p>'+data+'</p>').appendTo('body');
        });
  
        //버튼 이벤트
        $('#btn').click(function(){
            var msg = $('#msg').val();
            socket.emit('message', msg);
        });
    });
  </script>
 </head>
  
 <body>
  <input id="msg" type="text" style="width:100px;" />
  <input id="btn" type="button" value="send" />
 </body>
</html
Posted by august5pm
,

>npm install connect 

>npm install connect_router

>npm install socket.io


1. app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
    폴더구조
    1. html - html 페이지
    2. node_modules - nodejs 모듈
    3. Resource - js, css, images 등의 리소스 파일
*/
  
// 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);
        });
    });
}
  
/*
 * 클라이언트와 웹소켓 연결을 하기 위한 작업
 */
  
//필요한 모듈을 얻어온다.
var socketio = require("socket.io");
  
// 클라이언트와 소켓 통신을 하기 위한 io 객체를 얻어온다.
var io = socketio.listen(server);
  
//불필요한 로그는 제거 하기 위해
io.set("log level", 2);
  
// 클라이언트가 소켓 서버 접속을 하면 'connection' 이벤트가 발생한다.
io.sockets.on('connection', function(socket){
    /*
     * 클라이언트의 이벤트에 귀를 귀울이거나, 혹은 이벤트를 발생시키면 된다.
     *
     * 3가지 통신 방법
     * 1. public => io.sockets.emit("이벤트명", data);
     * 2. broadcast => io.broadcast.emit("이벤트명", data);
     * 3. private => io.sockets.sockets[id].emit("이벤트명", data);
     */
    console.log("connection");
    
    socket.on('name', name);
  
    //when the user disconnects.. perform this
    socket.on('disconnect', function(){
        console.log('disconect');
    });
  
    function name($data){
        socket.emit('name', $data);
    }
});


2. /html/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE HTML>
<html>
 <head>
  <title> socket.io </title>
  <script src="/socket.io/socket.io.js"></script>
  <script src="/js/jquery-1.8.0.min.js"></script>
  <script>
    $(document).ready(function(){
        var socket = io.connect('http://127.0.0.1:3000');
    
        // on connection to server, ask for user's name with an anonymous callback
        socket.on('connect', function(){
            
        });
        
        // addEventListener(event, callback)
        socket.on('name', name);
  
        $('#btn_send').click(function(){
            var inputValue = $('#input_text').val();
            socket.emit('name', inputValue);
        });
  
        function name($data){
            $("#result_text").html($data);
        }
    });
  </script>
 </head>
  
 <body>
    <input id="input_text" style="width:100px;" />
    <input id="btn_send" type="button" value="send" />
    <div id="result_text">result</div>
 </body>
</html>

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

[Node.js] net 모듈 + flash 소켓통신  (0) 2015.01.27
[nodeJS] Socket.IO 방만들기  (0) 2015.01.27
[nodeJS] Express / Routes / Jade 모듈  (0) 2015.01.27
[nodeJS] connect / connect_router 모듈  (0) 2015.01.27
[nodeJS] jade 모듈  (0) 2015.01.27
Posted by august5pm
,

>npm install express 

>npm install routes

>npm install jade


1. app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
    폴더 구조
    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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* 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('<h1>Life Page</h1>');
}
  
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

1
2
3
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
__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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!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"/>
 
    비밀번호<input type="text" name="pwd"/>
 
    <input type="submit" value="로그인"/>
</form>
</body>
</html>


4. /html/member/memIn.html

1
2
3
4
5
6
7
8
9
10
11
<!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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//모듈 추출
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

1
2
3
4
5
6
7
8
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//모듈 추출
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

1
2
3
4
5
6
<% 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 모듈 추가
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!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라는 파일을 생성하고 아래와 같이 코드를 입력 합니다.


1
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 파일을 생성하고 아래와 같이 코드를 입력합니다.


1
2
3
4
5
6
7
8
9
10
// 모듈 추출
var http = require('http');
  
// 웹 서버를 생성 및 실행
http.createServer(function (request, response){
    response.writeHead(200, {'Content-Type':'text/html'});
    response.end('<h1>Hello World</h1>');
}).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
,