오세헌

base source code

Showing 56 changed files with 937 additions and 0 deletions
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
let books = new Array();
app.get('/books/:bookId', (req, res) => {
let bookId = req.params.bookId;
console.log(books[bookId]);
res.send(books[bookId]);
});
/*
* json representation of book object
{
"id" : 2,
"name" : "book2",
"price" : 2000,
"author" : "jin"
}
*/
app.post('/books', (req, res) => {
// Create book information
books[req.body.id] = [req.body.id, req.body.name, req.body.price, req.body.author];
res.send(books[req.body.id]);
})
app.put('/books', (req, res) => {
// Update book information
})
app.delete('/books/:bookId', (req, res) => {
// Delete book information
})
let server = app.listen(80);
console.log(books);
{
"name": "assignment01",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2"
}
}
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let session = require('express-session')
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
let users = new Array();
users[0] = {
"userId" : 0,
"name" : "jin",
"password" : "abc",
"isAdmin" : true
}
app.put('/login', (req, res) => {
// users 배열에서 찾도록 처리 해야 함
// admin 여부를 확인하여 체크
// req.body.id : ID
// req.body.name : 패스워드
res.send("Login");
});
app.put('/logout', (req, res) => {
// Logout
// 세션 유효 여부를 체크하고 세션 Delete
req.session.userId = null;
res.send("LogOut");
});
let auth = (req, res, next) => {
// Session Check
// 어드민 여부 체크 필요
if (req.session.userId != null)
next();
else
res.send("Error");
};
app.get('/user/:userId', auth, (req, res) => {
// get User Information
res.send("OK");
});
// 사용자 추가 시에 admin 여부도 추가해야 함
let server = app.listen(80);
{
"name": "assignment02",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2",
"express-session": "^1.15.2"
}
}
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('hello world');
})
app.route('/book')
.get(function (req, res) {
res.send('Get a random book');
})
.post(function (req, res) {
res.send('Add a book');
})
.put(function (req, res) {
res.send('Update the book');
});
var server = app.listen(23023);
{
"name": "approute",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}
var express = require('express');
var app = express();
var birds = require('./birds');
app.get('/', function (req, res) {
res.send('hello world');
})
app.use('/birds',birds);
var server = app.listen(23023);
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('Birds home page');
})
router.get('/about', function (req, res) {
res.send('About birds');
});
module.exports=router;
{
"name": "expressrouter",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(23023, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
{
"name": "helloworld",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}
var express = require('express');
var app = express();
app.get('/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})
var cb0 = function (req, res, next) {
console.log("call by cb0");
next()
}
var cb1 = function (req, res, next) {
console.log("call by cb1");
res.send('Hello from C!')
}
app.get('/c', [cb0, cb1])
var server = app.listen(23023);
{
"name": "multiplehandler",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
app.get('/', function(req, res) {
res.render('index', { title: 'OSS Page' });
});
var server = app.listen(23023);
{
"name": "render",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^2.5.6",
"express": "^4.15.2"
}
}
var express = require('express');
var app = express();
app.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params);
})
var server = app.listen(23023);
{
"name": "routeparameter",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}
var express = require('express');
var app = express();
// The routing path matches requests to /about
app.get('/about', function (req, res) {
res.send('about')
})
// The routing path matches requests to /random.text
app.get('/random.text', function (req, res) {
res.send('random.text')
})
// This route path matches abcd, abxcd, abRANDOMcd, ab123cd, and so on.
app.get('/ab*cd', function (req, res) {
res.send('ab*cd')
})
var server = app.listen(23023);
{
"name": "routingpath",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}
var express = require('express');
var app = express();
var session = require('express-session')
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
app.get('/', function(req, res, next) {
var sess = req.session;
console.log(req.session);
if (sess.views) {
sess.views++;
res.send("session Views " + sess.views);
res.send();
} else {
req.session.views = 1;
res.send("welcome to the session demo. refresh!");
res.end();
}
});
var server = app.listen(23023);
{
"name": "session",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2",
"express-session": "^1.15.2"
}
}
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('hello world');
})
var server = app.listen(23023);
{
"name": "simplerouting",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}
var express = require('express');
var app = express();
app.all('/', function (req, res, next) {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})
app.get('/', function (req, res) {
res.send('hello world');
})
app.post('/', function (req, res) {
res.send('POST request to the homepage')
})
var server = app.listen(23023);
{
"name": "specialrouting",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(23023);
{
"name": "staticfiles",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2"
}
}
// 모듈을 읽어 들입니다.
const request = require('request');
// 요청을 위한 상수를 선언합니다: TOKEN은 자신의 것을 입력해주세요.
const TARGET_URL = 'https://notify-api.line.me/api/notify';
const TOKEN = '///채워주세요///';
// 요청합니다.
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
form: {
message: '안녕하세요. LINE Notify 테스트입니다.',
stickerPackageId: 1,
stickerId: 1
}
},(error, response, body) => {
console.log(body)
});
{
"name": "notify",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"request": "^2.88.2"
}
}
const request = require('request');
const TARGET_URL = 'https://api.line.me/v2/bot/message/push'
const MULTI_TARGET_URL = 'https://api.line.me/v2/bot/message/multicast'
const BROAD_TARGET_URL = 'https://api.line.me/v2/bot/message/broadcast'
const TOKEN = '채널 토큰으로 교체'
const USER_ID = '사용자의 ID, 메세지 수신 시에 확인할 수 있음'
// Single User
// request.post(
// {
// url: TARGET_URL,
// headers: {
// 'Authorization': `Bearer ${TOKEN}`
// },
// json: {
// "to": `${USER_ID}`,
// "messages":[
// {
// "type":"text",
// "text":"Hello, user"
// },
// {
// "type":"text",
// "text":"May I help you?"
// }
// ]
// }
// },(error, response, body) => {
// console.log(body)
// });
// Multicast User
// request.post(
// {
// url: MULTI_TARGET_URL,
// headers: {
// 'Authorization': `Bearer ${TOKEN}`
// },
// json: {
// "to": [`${USER_ID}`],
// "messages":[
// {
// "type":"text",
// "text":"Hello, user"
// },
// {
// "type":"text",
// "text":"May I help you?"
// }
// ]
// }
// },(error, response, body) => {
// console.log(body)
// });
// Broadcast
request.post(
{
url: BROAD_TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"messages":[
{
"type":"text",
"text":"Hello, user"
},
{
"type":"text",
"text":"May I help you?"
}
]
}
},(error, response, body) => {
console.log(body)
});
\ No newline at end of file
{
"name": "push",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"request": "^2.88.2"
}
}
var express = require('express');
const request = require('request');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = '채널 토큰으로 변경'
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const domain = "도메인 변경"
const sslport = 23023;
const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/hook', function (req, res) {
var eventObj = req.body.events[0];
var source = eventObj.source;
var message = eventObj.message;
// request log
console.log('======================', new Date() ,'======================');
console.log('[request]', req.body);
console.log('[request source] ', eventObj.source);
console.log('[request message]', eventObj.message);
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":eventObj.replyToken,
"messages":[
{
"type":"text",
"text":"Hello, user"
},
{
"type":"text",
"text":"May I help you?"
}
]
}
},(error, response, body) => {
console.log(body)
});
res.sendStatus(200);
});
try {
const option = {
ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
};
HTTPS.createServer(option, app).listen(sslport, () => {
console.log(`[HTTPS] Server is started on port ${sslport}`);
});
} catch (error) {
console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
console.log(error);
}
{
"name": "reply",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"request": "^2.88.2"
}
}
const express = require('express');
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const app = express();
// 본인이 소유한 도메인으로 변경해야 함
// www 붙여야 함
const domain = "www.stagefive.tk"
const sslport = 23023;
app.get('/', function (req, res) {
res.send('Hello World');
})
try {
const option = {
ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
};
HTTPS.createServer(option, app).listen(sslport, () => {
console.log(`[HTTPS] Server is started on port ${sslport}`);
});
} catch (error) {
console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
console.log(error);
}
{
"name": "ssl",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
var express = require('express');
const request = require('request');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = '채널 토큰'
const PAPAGO_URL = 'https://openapi.naver.com/v1/papago/n2mt'
const PAPAGO_ID = '파파고 ID'
const PAPAGO_SECRET = '파파고 Client Secret'
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const domain = "도메인 명"
const sslport = 23023;
const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/hook', function (req, res) {
var eventObj = req.body.events[0];
var source = eventObj.source;
var message = eventObj.message;
// request log
console.log('======================', new Date() ,'======================');
console.log('[request]', req.body);
console.log('[request source] ', eventObj.source);
console.log('[request message]', eventObj.message);
trans(eventObj.replyToken, eventObj.message.text);
res.sendStatus(200);
});
function trans(replyToken, message) {
request.post(
{
url: PAPAGO_URL,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Naver-Client-Id': `${PAPAGO_ID}`,
'X-Naver-Client-Secret': `${PAPAGO_SECRET}`
},
body: 'source=ko&target=en&text=' + message,
json:true
},(error, response, body) => {
if(!error && response.statusCode == 200) {
console.log(body.message);
var transMessage = body.message.result.translatedText;
request.post(
{
url: TARGET_URL,
headers: {
'Authorization': `Bearer ${TOKEN}`
},
json: {
"replyToken":replyToken,
"messages":[
{
"type":"text",
"text":transMessage
}
]
}
},(error, response, body) => {
console.log(body)
});
}
});
}
try {
const option = {
ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
};
HTTPS.createServer(option, app).listen(sslport, () => {
console.log(`[HTTPS] Server is started on port ${sslport}`);
});
} catch (error) {
console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
console.log(error);
}
\ No newline at end of file
{
"name": "trans",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"request": "^2.88.2"
}
}
var express = require('express');
const bodyParser = require('body-parser');
var app = express();
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const domain = "도메인 변경 처리"
const sslport = 23023;
app.use(bodyParser.json());
app.post('/hook', function (request, response) {
var eventObj = request.body.events[0];
// request log
console.log('======================', new Date() ,'======================');
response.sendStatus(200);
});
try {
const option = {
ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
};
HTTPS.createServer(option, app).listen(sslport, () => {
console.log(`[HTTPS] Server is started on port ${sslport}`);
});
} catch (error) {
console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
console.log(error);
}
{
"name": "webhook",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
}
// 아래 2개의 함수를 모듈로 정의하는 것이 필요함
function add(a,b) {
return a+b;
}
function sub(a,b) {
return a-b;
}
const doSomethingAsync = () => {
return new Promise(resolve => {
setTimeout(() => resolve('I did something'), 3000)
})
}
// doSomething 함수를 async await 형태로 변경하시오
const doSomething = () => {
doSomethingAsync().then( a => console.log(a))
}
console.log('Before')
doSomething()
console.log('After')
var events = require('events');
var eventEmitter = new events.EventEmitter();
var connectHandler = function connected() {
console.log('connection successful.');
eventEmitter.emit('data_received');
}
eventEmitter.on('connection', connectHandler);
eventEmitter.on('data_received', function(){
console.log('data received successfully.');
});
eventEmitter.emit('connection');
console.log("Program Ended.");
var events = require('events');
var eventEmitter = new events.EventEmitter();
var listner1 = function listner1() {
console.log('listner1 executed.');
}
var listner2 = function listner2() {
console.log('listner2 executed.');
}
eventEmitter.addListener('connection', listner1);
eventEmitter.on('connection', listner2);
var eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
eventEmitter.emit('connection');
eventEmitter.removeListener('connection', listner1);
console.log("Listner1 will not listen now.");
eventEmitter.emit('connection');
eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
console.log("Program Ended.");