반응형

[AWS] lambda와 EC2/ECS 비교




 Amazon EC2/ECS 

 AWS Lambda

  • 시간단위 리소스 대여
  • 유연한 인프라 설계 (OS/타입)
  • 장애에 대한 고려 필요
  • 인스턴스 추가를 통한 확장
  • 모든 코드 및 언어로 개발 가능
  • 서버 관리 부담 있음
  • 이벤트 요청에 따라서 사용
  • OS/타입 등 인프라 고려 필요 없음
  • AWS 기반 무장애 시스템
  • 요청량에 따라 확장
  • Node.js 및 자바 코드로 함수 구현
  • 서버 관리 부담 없음


SSH를 사용하여 Linux 인스턴스에 연결

http://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html



...

반응형
반응형

MEAN (Mongo, Express, Angular, Node) - A Simple, Scalable and Easy starting point for full stack javascript web development - utilizing many of the best practices we've found on the way 



https://github.com/linnovate/mean


MEAN is based on the next technologies

  • Angular4 web starter
  • Innograph (uses GraphQL for schema standartization)
  • Bit - manages components, services and schemas

If you're looking for the classic angular-1.x version of mean it has moved to this 1.x branch


Node.js를 위한 빠르고 개방적인 간결한 웹 프레임워크

http://expressjs.com/ko/


KEYNOTE: Express, State of the Union by Doug Wilson, Express




MongoDB : https://www.mongodb.com/download-center#atlas


MongoDB Getting Started : https://docs.mongodb.com/manual/tutorial/getting-started/



Angularjs


구  : https://angularjs.org/


신  : https://angular.io/



AngularJS Getting Started : https://angular.io/guide/quickstart


Angular2 Videos


...

반응형
반응형

[Node.js] npm 소개와 설치


이제 자바스크립트 라이브러리를 찹아보면 왠만하면 node.js에 들어가있다. 

결국 서버사이트로 가는거지. 


내장 http서버 라이브러리를 가지고 있기 때문에 설치만 하면 뚝딱 웹서비스가 돌아간다. 

이걸 서비스에 언제 적용할지가 문제.


npm이란 Node Package Modules의 약자다. Node.js에서 사용가능한 모듈들을 패키지화시켜 모아놓은 것이다.


이것을 설치하고 나면 나중에 업데이트도 쉽고 좋다. 


npm 홈페이지 : https://www.npmjs.org/



물론 개별 설치해서 사용해도 된다. 


Node.js 다운로드 사이트 : http://nodejs.org/download/


Guide :  https://nodejs.org/en/docs/guides/



-----------------------------------------------------------


http://mean.io/


MEAN Stack 을 선호하기도 한다. 


Mongodb + Express + Angularjs + Nodejs




...

반응형
반응형

[Node.js] 실시간 멀티채팅 구현하기!  - http://jinblog.kr/156



Node.js - https://nodejs.org/en/


Socket.io - https://socket.io/



Github 공개된 소스 : https://github.com/devjin0617/nodejs-socket.io-chat-example



nodejs-socket.io-chat-example

this is chat example using nodejs with socket.io

how to run

npm module install:

console$ cd /path/to/project
console$ npm install
  1. start socket.io server

using port 50000

console$ npm run socket
  1. start simple web server
console$ npm run web

using port 8000

  1. open your browser and connect to localhost:8000

...

반응형
반응형

[ChatBot] 챗봇 시작해보기

챗봇 시작해보기

  1. 1. 챗봇 시작해보기 파이썬과 노드로 만들어 보는 챗봇 (Slack, facebook..) ABCD, 한성일
  2. 2. 0. 챗봇이란?
  3. 3. 챗봇이란? 고객의 요청을 대신 응답해주는 채팅로봇 인공지능 빅데이터 자연어처리 프로그래밍 나이가 어떻게 되 시나요? 텍스트 음성 … 묻지 마세요.. 응답요청 Chatbot 머신러닝
  4. 4. 챗봇 예 심심이 페이스북 챗봇
  5. 5. 어디에 쓸까요? 가장 쉽게 떠오르는 곳은 콜 센터입니다.
  6. 6. 또 어디가 있을까요? 물건주문, 호텔예약, 비서…
  7. 7. 생각보다 간단할지 모릅니다.
  8. 8. 1. 챗봇 플로우
  9. 9. 챗봇 프레임웍 http://kitt.ai/ https://dev.botframework.com/
  10. 10. 챗봇 플랫폼 라인 슬렉 텔레그램 페이스북
  11. 11. 일반적인 챗봇 플로우 http://www.lds.com/coepost/enabling-a-smart-user-experience-using-chatbots/
  12. 12. 슬랙과 페이스북 API 를 이용해서 챗봇을 만들어보겠습니다. 간단한..
  13. 13. 2. 파이썬으로 슬렉챗봇 만들기
  14. 14. 선작업 1. 파이썬 설치 https://realpython.com/blog/python/getting-started-with-the-slack-api-using-python-and-flask/ 참고 2. 슬랙 커뮤니티 생성
  15. 15. VIRTUAL ENV 설정 $ mkdir abcd-python-slack-bot $ virtualenv venv $ source venv/bin/activate (venv)$ pip install slackclient==1.0.0
  16. 16. 토큰생성 https://api.slack.com/web
  17. 17. 토큰생성 https://api.slack.com/docs/oauth-test-tokens
  18. 18. 토큰을 환경 변수로 지정 (venv)$ export SLACK_TOKEN=‘생성된 토큰'
  19. 19. ngrok 을 이용 외부 오픈 SSL 주소 생성 https://ngrok.com/download (venv)$ ./ngrok http 5000 로컬 서버를 SSL 로 외부 오픈..
  20. 20. WEBHOOK https://api.slack.com/outgoing-webhooks
  21. 21. WEBHOOK https://abcds.slack.com/apps/new/A0F7VRG6Q-outgoing-webhooks
  22. 22. INTEGRATION SETTINGS https://abcds.slack.com/services/B37GEBQBZ?added=1 ngrok 으로 생성된 주소 + /webhook 사용될 채널 웹훅 토큰
  23. 23. WEBHOOK (venv)$ export SLACK_WEBHOOK_SECRET=‘생성된 웹훅 토큰'
  24. 24. FLASK 설치 (venv)$ pip install flask
  25. 25. RECEIVE.PY # -*- coding: utf-8 -*- import os from flask import Flask, request, Response from slackclient import SlackClient app = Flask(__name__) SLACK_WEBHOOK_SECRET = os.environ.get('SLACK_WEBHOOK_SECRET') SLACK_TOKEN = os.environ.get('SLACK_TOKEN', None) slack_client = SlackClient(SLACK_TOKEN) def send_message(channel_id, message): slack_client.api_call( "chat.postMessage", channel=channel_id, text=message, username='abcdBot', icon_emoji=':monkey_face:' ) @app.route('/webhook', methods=['POST']) def inbound(): print("get " + request.form.get('token')) print("username " + request.form.get('user_name')) username = request.form.get('user_name') if request.form.get('token') == SLACK_WEBHOOK_SECRET and username != 'slackbot': channel_name = request.form.get('channel_name') channel_id = request.form.get('channel_id') username = request.form.get('user_name') text = request.form.get('text') inbound_message = username + " in " + channel_name + " says: " + text send_message(channel_id, unicode("따라쟁이 ", 'utf-8') + " " + text) print(inbound_message) return Response(), 200 @app.route('/', methods=['GET']) def test(): return Response('It works!') if __name__ == "__main__": app.run(debug=True) receive.py
  26. 26. RECEIVE.PY (venv)$ python receive.py
  27. 27. 구동화면
  28. 28. 실제 서버를 설정해서 포팅해봅시다.
  29. 29. 3. 노드로 페이스북 챗봇 만들기 (HEROKU)
  30. 30. 선작업 http://x-team.com/2016/04/how-to-get-started-with-facebook-messenger-bots/ nodejs 설치 참고 https://nodejs.org/ko/download/
  31. 31. 선작업 heroku 가입이 되어있어야 함 https://heroku.com/ https://devcenter.heroku.com/articles/getting-started-with-nodejs#set-up heroku CLI 가 설치되어있어야 함
  32. 32. 프로젝트 생성 $ mkdir abcd-node-bot $ cd abcd-node-bot/ $ npm init $ npm install express body-parser request --save { "name": "testbot", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo "Error: no test specified" && exit 1", "start": "node index.js" }, "author": "", "license": "ISC", "dependencies": { "body-parser": "^1.15.2", "express": "^4.14.0", "request": "^2.79.0" } }
  33. 33. express 설치 $ npm install express body-parser request --save
  34. 34. INDEX.JS 생성 index.js 생성 var express = require('express'); var bodyParser = require('body-parser'); var request = require('request'); var app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.listen((process.env.PORT || 3000)); // Server frontpage app.get('/', function (req, res) {     res.send('잘돈다.'); }); // Facebook Webhook app.get('/webhook', function (req, res) { console.log(req.query['hub.verify_token']); if (req.query['hub.verify_token'] === 'abcd_verify_token') { // webhook 설정에 입력된 토큰 res.send(req.query['hub.challenge']); } else { res.send('Invalid verify token'); } }); node index.js
  35. 35. HEROKU 생성 $ heroku login
  36. 36. 로컬 GIT 설정 $ git init $ heroku create $ git add . $ git commit -m ‘ABCD 노드 봇 첫번째 커밋' $ git push heroku master .gitignore node_modules
  37. 37. 작동확인 https://warm-spire-76279.herokuapp.com/
  38. 38. 페이스북 페이지 만들기 https://www.facebook.com/pages/create/
  39. 39. 페이지 생성 완료
  40. 40. 앱생성 https://developers.facebook.com/quickstarts/ 기본설정으로 앱생성
  41. 41. 제품추가
  42. 42. 토큰생성
  43. 43. 토큰생성
  44. 44. WEB HOOK 설정 https://developers.facebook.com/ heroku 경로
  45. 45. WEB HOOK 설정 페이지를 선택해주세요!
  46. 46. WEBHOOK 설정
  47. 47. PAGE_ACCESS_TOKEN 설정 PAGE_ACCESS_TOKEN
  48. 48. 토큰 유효성 확인 https://warm-spire-76279.herokuapp.com/webhook? hub.verify_token=abcd_verify_token
  49. 49. 따라하기 봇 테스트
  50. 50. KITTEN https://placekitten.com/ kitten 300 200
  51. 51. 따라하기 & 키튼 봇 소스 1 var express = require('express'); var bodyParser = require('body-parser'); var request = require('request'); var app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.listen((process.env.PORT || 3000)); // Server frontpage app.get('/', function (req, res) { res.send('This is TestBot Server'); }); // Facebook Webhook app.get('/webhook', function (req, res) { console.log(req.query['hub.verify_token']); if (req.query['hub.verify_token'] === 'abcd_verify_token') { // webhook 설정에 입력된 토큰 res.send(req.query['hub.challenge']); } else { res.send('Invalid verify token'); } });
  52. 52. 따라하기 & 키튼 봇 소스 2 // handler receiving messages app.post('/webhook', function (req, res) { var events = req.body.entry[0].messaging; for (i = 0; i < events.length; i++) { var event = events[i]; if (event.message && event.message.text) { if (!kittenMessage(event.sender.id, event.message.text)) { sendMessage(event.sender.id, {text: event.message.text}); } } else if (event.postback) { console.log("Postback received: " + JSON.stringify(event.postback)); } } res.sendStatus(200); }); // generic function sending messages function sendMessage(recipientId, message) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: process.env.PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: recipientId}, message: message, } }, function(error, response, body) { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } }); };
  53. 53. 따라하기 & 키튼 봇 소스 3 // send rich message with kitten function kittenMessage(recipientId, text) { text = text || ""; var values = text.split(' '); if (values.length === 3 && values[0] === 'kitten') { if (Number(values[1]) > 0 && Number(values[2]) > 0) { var imageUrl = "https://placekitten.com/" + Number(values[1]) + "/" + Number(values[2]); message = { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": [{ "title": "Kitten", "subtitle": "Cute kitten picture", "image_url": imageUrl , "buttons": [{ "type": "web_url", "url": imageUrl, "title": "Show kitten" }, { "type": "postback", "title": "I like this", "payload": "User " + recipientId + " likes kitten " + imageUrl, }] }] } } }; sendMessage(recipientId, message); return true; } } return false; };
  54. 54. 4. 조금 더해보기
  55. 55. 더하기봇
  56. 56. 더하기 봇 소스 #1 var express = require('express'); var bodyParser = require('body-parser'); var request = require('request'); var app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.listen((process.env.PORT || 3000)); // Server frontpage app.get('/', function (req, res) { res.send('This is TestBot Server'); }); app.get('/forecast', function (req, res) { forecast.get([35.9335, 139.6181], function(err, weather) { if(err) return console.dir(err); console.dir(weather); console.dir(weather.latitude); console.log("weather.latitude " + weather.latitude); console.log("오늘 " + weather.timezone + "의 날씨는 " + weather.currently.summary + "입니다. "); }); res.send('forecast'); });
  57. 57. 더하기 봇 소스 #2 // Facebook Webhook app.get('/webhook', function (req, res) { if (req.query['hub.verify_token'] === 'abcd_verify_token') { res.send(req.query['hub.challenge']); } else { res.send('Invalid verify token'); } }); // handler receiving messages app.post('/webhook', function (req, res) { var events = req.body.entry[0].messaging; for (i = 0; i < events.length; i++) { var event = events[i]; if (event.message && event.message.text) { addMessage(event.sender.id, event.message.text); } } res.sendStatus(200); });
  58. 58. 더하기 봇 소스 #3 // generic function sending messages function sendMessage(recipientId, message) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: process.env.PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: recipientId}, message: message, } }, function(error, response, body) { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } }); }; function addMessage(recipientId, text) { text = text || ""; var values = text.split(' '); if (values.length === 3 && values[0] === 'add') { if (Number(values[1]) > 0 && Number(values[2]) > 0) { addText = values[1] + " + " + values[2] + " = " + (Number(values[1]) + Number(values[2])); message = {text: addText}; sendMessage(recipientId, message); } } };
  59. 59. FORECAST 설치 $ npm install --save forecast
  60. 60. 날씨봇 https://darksky.net/dev/
  61. 61. FORECAST KEY
  62. 62. 날씨앱 테스트
  63. 63. 날씨 봇 소스 #1 var express = require('express'); var bodyParser = require('body-parser'); var request = require('request'); var app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.listen((process.env.PORT || 3000)); var Forecast = require('forecast'); // Initialize var forecast = new Forecast({ service: 'darksky', key: ‘your-api-key‘, units: 'celcius', cache: true, // Cache API requests ttl: { minutes: 27, seconds: 45 } });
  64. 64. 날씨 봇 소스 #2 // Server frontpage app.get('/', function (req, res) { res.send('This is TestBot Server'); }); app.get('/forecast', function (req, res) { forecast.get([35.9335, 139.6181], function(err, weather) { if(err) return console.dir(err); console.dir(weather); }); res.send('forecast'); }); // Facebook Webhook app.get('/webhook', function (req, res) { if (req.query['hub.verify_token'] === 'abcd_verify_token') { res.send(req.query['hub.challenge']); } else { res.send('Invalid verify token'); } });
  65. 65. 날씨 봇 소스 #3 // handler receiving messages app.post('/webhook', function (req, res) { var events = req.body.entry[0].messaging; for (i = 0; i < events.length; i++) { var event = events[i]; if (event.message && event.message.text) { weatherMessage(event.sender.id, event.message.text); } } res.sendStatus(200); }); // generic function sending messages function sendMessage(recipientId, message) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: process.env.PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: recipientId}, message: message, } }, function(error, response, body) { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } }); };
  66. 66. 날씨 봇 소스 #4 function weatherMessage(recipientId, text){ text = text || ""; var values = text.split(' '); if (values[0] === '날씨') { forecast.get([35.9335, 139.6181], function(err, weather) { console.log(weather); weatherText = "오늘 " + weather.timezone + "의 날씨는 " + weather.currently.summary + "입니다. "; message = {text: weatherText}; sendMessage(recipientId, message); }); } }
  67. 67. 더하기와 날씨봇을 확장해 보세요.
  68. 68. 또 어떤걸 해보고 싶으신가요? 머신러닝, 자연어처리, 음성인식…
  69. 69. 파이썬 https://github.com/snowkiwi/slack-python-bot-tutorial 소스는 이곳을 참고하세요. 노드 https://github.com/snowkiwi/facebook-node-bot
  70. 70. Q & A
  71. 71. 수고하셨습니다. :) ABCD http://abcds.kr 


...

반응형
반응형

Node.js, Express, MongoDB를 이용하여 REST API 만들기  http://mobicon.tistory.com/197


원문 : http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/



Installing Node.js

  1. Go to http://nodejs.org, and click the Install button.
  2. Run the installer that you just downloaded. When the installer completes, a message indicates that Node was installed at /usr/local/bin/node and npm was installed at /usr/local/bin/npm.

Installing Express

Express is a lightweight node.js web application framework. It provides the basic HTTP infrastructure that makes it easy to create REST APIs.

Installing MongoDB

To install MongoDB on your specific platform, refer to the MongoDB QuickStart. Here are some quick steps to install MongoDB on a Mac:

  1. Open a terminal window and type the following command to download the latest release:

    curl http://downloads.mongodb.org/osx/mongodb-osx-x86_64-2.2.0.tgz > ~/Downloads/mongo.tgz

    Note: You may need to adjust the version number. 2.2.0 is the latest production version at the time of this writing.

  2. Extract the files from the mongo.tgz archive:

    cd ~/Downloads
    tar -zxvf mongo.tgz

  3. Move the mongo folder to /usr/local (or another folder according to your personal preferences):

    sudo mv -n mongodb-osx-x86_64-2.2.0/ /usr/local/

  4. (Optional) Create a symbolic link to make it easier to access:

    sudo ln -s /usr/local/mongodb-osx-x86_64-2.2.0 /usr/local/mongodb

  5. Create a folder for MongoDB’s data and set the appropriate permissions:

    sudo mkdir -p /data/db
    sudo chown `id -u` /data/db

  6. Start mongodb

    cd /usr/local/mongodb
    ./bin/mongod

  7. You can also open the MongoDB Interactive Shell in another terminal window to interact with your database using a command line interface.

    cd /usr/local/mongodb
    ./bin/mongo

    Refer to the MongoDB Interactive Shell documentation for more information.

Installing the MongoDB Driver for Node.js

There are different solutions offering different levels of abstraction to access MongoDB from Node.js (For example, Mongoose and Mongolia). A comparaison of these solutions is beyond the scope of this article. In this, guide we use the native Node.js driver.

To install the the native Node.js driver, open a terminal window, cd to your nodecellar folder, and execute the following command:

npm install mongodb







.




반응형
반응형

node.js - 윈도우 설치하기

 

http://nodejs.org/download 에 가서 Windows Installer (.msi)를 받아서 설치.

 

https://nodejs.org/en/

 

안정버전 V5.0으로 다운받아서 설치.

 

설치 후 node.js 콘솔창에서 입력도 가능하고,  .js 파일 생성 후

도스 창에서 $node 해당파일.js 를 실행 할 수 있다.

 

콘솔창을 종료시키고 싶으면 Ctrl + C 두 번!

 

 

아니면 Express를 사용해서 설치 가능하다.  http://expressjs.com/ 

 

Installing

Assuming you’ve already installed Node.js, create a directory to hold your application, and make that your working directory.

$ mkdir myapp
$ cd myapp

Use the npm init command to create a package.json file for your application. For more information on how package.json works, see Specifics of npm’s package.json handling.

$ npm init

This command will prompt your for a number of things such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, except for:

entry point: (index.js)

Enter app.js or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the suggested default file name.

Now install Express in the app directory and save it in the dependencies list:

$ npm install express --save

To install Express temporarily, and not add it to the dependencies list, omit the --save option:

$ npm install express

Node modules installed with the --save option are added to the dependencies list in the package.json file. Then usingnpm install in the app directory will automatically install modules in the dependencies list.

 

 

 

 

 

반응형
반응형

Paperclip.js: A powerful template engine for Node.js and the browser

 

Paperclip.js is a powerful template engine that’s built for extensibility and speed. It creates compiled templates for the browser and Node.js.

paperclip.js

reactive DOM template engine built for speed, and extensibility 

 

 

 

 

 

 

 

 

반응형

+ Recent posts