node.js 설치
node.js 최신 패키지를 wget 명령으로 다운로드하고 dpkg로 설치한다.
$ sudo wget http://node-arm.herokuapp.com/node_latest_armhf.deb $ sudo dpkg -i node_latest_armhf.deb
express 설치
$ npm install -g express $ npm install -g express-generator
express로 http 서버 실행하기
server.js 파일 생성
var express = require('express'), http = require('http'), app = express(), server = http.createServer(app); app.get('/hello', function(req, res) { res.sendfile('hello.html', {root : __dirname }) ; }); server.listen(8000, function() { console.log('express server listening on port ' + server.address().port) });
hello.html 파일 생성
<!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <h1>Hello World!</h1> </body> </html>
서버 실행
$ node server.js
브라우저에서 port 8000번 url /hello로 접속
ex) 라즈베리파이의 ip가 192.168.1.241인 경우 http://192.168.1.241:8000/hello 접속
express 명령으로 프로젝트 생성
$ express [프로젝트 이름]
위와 같이 express 명령을 이용하여 프로젝트를 생성 가능 (참고 : express-generator를 설치하지 않은 경우 express 명령이 없을 수 있음)
ex)
$ express hello
다음과 같이 새로운 프로젝트가 생성된다.
pi@raspberrypi:~/tmp$ express hello warning: the default view engine will not be jade in future releases warning: use `--view=jade' or `--help' for additional options create : hello create : hello/package.json create : hello/app.js create : hello/public create : hello/routes create : hello/routes/index.js create : hello/routes/users.js create : hello/views create : hello/views/index.jade create : hello/views/layout.jade create : hello/views/error.jade create : hello/bin create : hello/bin/www create : hello/public/javascripts create : hello/public/images create : hello/public/stylesheets create : hello/public/stylesheets/style.css install dependencies: $ cd hello && npm install run the app: $ DEBUG=hello:* npm start
설명에서 나온대로 npm install 명령과 npm start 명령으로 서버를 구동하여 보자.
$ cd hello $ npm install $ DEBUG=hello:* npm start
npm install을 실행하면 아래와 같이 의존 패키지들을 설치하여 준다.
pi@raspberrypi:~/tmp/hello$ npm install npm WARN deprecated jade@1.11.0: Jade has been renamed to pug, please install the latest version of pug instead of jade npm WARN deprecated transformers@2.1.0: Deprecated, use jstransformer debug@2.6.9 node_modules/debug mqq ms@2.0.0 serve-favicon@2.4.5 node_modules/serve-favicon tqq ms@2.0.0 tqq fresh@0.5.2 tqq parseurl@1.3.2 tqq etag@1.8.1 mqq safe-buffer@5.1.1 cookie-parser@1.4.3 node_modules/cookie-parser tqq cookie-signature@1.0.6 mqq cookie@0.3.1 .....
다음으로 npm start를 하면 아래와 같이 브라우저로 사이트 접속이 가능하다. 기본 port는 3000이다.
pi@raspberrypi:~/tmp/hello$ DEBUG=hello:* npm start > hello@0.0.0 start /home/pi/tmp/hello > node ./bin/www hello:server Listening on port 3000 +0ms