버퍼(buffer)
- 메모리에 저장되는 일부 공간
- 바이트 단위로 저장되며 integer 형태의 배열
const buf = Buffer.from('Hi');
console.log(buf);
console.log(buf.length);
console.log(buf[0]);
console.log(buf[1]);
console.log(buf.toString());
const buf2 = Buffer.alloc(2);
buf2[0] = 72;
buf2[1] = 105;
console.log(buf2.toString());
console.log('-------------')
// nodejs 를 메모리 버퍼에 문자열 사이즈 만큼 메모리를 할당하고 문자를 저장 후 출력
// 단 아스키코드를 사용
const buf3 = Buffer.alloc(6);
buf3[0] = 110;
buf3[1] = 111;
buf3[2] = 100;
buf3[3] = 101;
buf3[4] = 106;
buf3[5] = 115;
console.log(buf3.toString());
const newBuf = Buffer.concat([buf, buf2, buf3]);
console.log(newBuf.toString());
스트림(Stream)
- 데이터의 흐름을 나타내며 데이터를 읽는 스트림, 데이터를 쓰는 스트림, 데이터를 읽고 쓰는 스트림 등이 있음
- 일반적으로 데이터를 효율적으로 처리하고 메모리 사용량을 최적화하기 위해 사용
const fs = require('fs');
const beforeMem = process.memoryUsage().rss;
console.log(beforeMem);
fs.readFile('./test.html', (_, data) => {
fs.writeFile('./file.txt', data, () => {
console.log('파일 저장 완료');
});
const afterMem = process.memoryUsage().rss;
const diff = afterMem - beforeMem;
const result = diff / 1024 / 1024;
console.log(diff);
console.log(`메모리 사용: ${result} MB`);
});
pipe()
- 스트림을 연결하고 데이터를 한 스트림에서 다른 스트림으로 자동으로 전달하는 메서드.
- 데이터를 효율적으로 처리하고 복사하지 않고도 한 스트림에서 다른 스트림으로 데이터를 전달할 수 있음
const fs = require('fs');
const zlib = require('zlib');
const readStream = fs.createReadStream('file.txt');
const zlibStream = zlib.createGzip();
const writeStream = fs.createWriteStream('./file2.txt.gz');
const piping = readStream.pipe(zlibStream).pipe(writeStream);
piping.on('finish', () => {
console.log('끝!');
});
http 모듈
- 웹 서버와 클라이언트를 만들고 관리하는 데 사용되는 핵심 모듈
- HTTP 서버를 만들거나 HTTP 클라이언트 요청을 만들 수 있음
package.json 기본값으로 생성하기
npm init -y
라이브러리 설치
npm install 패키지명
npm i 패키지명
nodemon 설치
npm i nodemon --save-dev
템플릿 엔진
- 웹 어플리케이션에서 동적으로 HTML을 생성하는데 사용하는 도구 및 라이브러리
- HTML 페이지 내에서 데이터를 동적으로 삽입하고 조작하는 데 도움이 되며, 주로 웹 어플리케이션에서 뷰 부분을 생성하는데 활용
- EJS, Pug, Handlebars, Nunjucks ...
- ejs 공식 홈페이지(https://ejs.co)
REST(Representational State Transfer)
자원을 이름으로 구분하여 해당 자원의 상태를 주고 받는 모든 것을 의미
REST API
REST 기반으로 서비스 API를 구현한 것
API(Application Programming Interface)
기능의 집합을 제공해서 컴퓨터 프로그램간의 상호작용을 하도록 하는 것
CRUD Operation
POST: 생성(create)
GET: 조회(read)
PUT: 수정(update)
DELETE: 삭제(delete)
Express 웹 프레임워크
- 웹 서버를 생성하고 HTTP 요청에 대한 라우팅 및 처리, 미들웨어를 통한 요청 및 응답 처리등을 간단하게 구현할 수 있음
- 다양한 확장 기능과 모듈을 제공하여 개발 생산성을 높일 수 있음
- npm i express
import express from 'express';
// 객체 생성
const app = express();
// 미들웨어
// next: 다음 미들웨어를 호출
app.use((req, res, next) => {
res.setHeader('node-skill', 'node.js는 너무 재밌어!');
next();
});
// app.use((req, res, next) => {
// res.send('<h2>페이지를 찾을 수 없습니다</h2>');
// });
app.get('/', (req, res, next) => {
res.send('<h2>익스프레스 서버로 만든 첫번째 페이지</h2>');
next();
});
app.get('/hello', (req, res, next) => {
res.setHeader('Content-Type', 'application/json')
res.status(200).json({userid:'apple', name:'김사과', age:20});
next();
});
// 서버 실행
app.listen(8080);
import express from 'express';
import bodyParser from 'body-parser';
//npm i body-parser
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', (req, res) => {
res.send('<h2>로그인</h2><form action="/login" method="post"><p>아이디: <input type="text" name="userid" id="userid"></p><p>비밀번호: <input type="password" name="userpw" id="userpw"></p><p><button type="submit">로그인</button></p></form>');
});
// localhost:8080/posts
// localhost:8080/posts?id=1
// localhost:8080/posts?id=1&userid=apple&name=김사과
app.get('/posts', (req,res) => {
console.log('posts 호출!')
console.log('path: ', req.path);
console.log('query:', req.query);
res.sendStatus(200);
});
// localhost:8080/posts/1
// localhost:8080/posts/1?id=10
app.get('/posts/:id', (req, res) => {
console.log('posts 호출!')
console.log('path: ', req.path);
console.log('query:', req.query);
console.log('params:', req.params);
res.sendStatus(200);
})
// localhost:8080/mypage
// localhost:8080/myroom
app.get(['/mypage', '/myroom'], (req, res) => {
console.log('path: ', req.path);
res.send(`<h2> ${req.path} 페이지!! </h2>`);
});
// localhost:8080/10
// app.get('/member/:userid', (req, res) => {
// console.log(req.path, '호출!');
// console.log(`${req.params.userid}번 멤버가 출력됨!`);
// res.sendStatus(200);
// });
// http://localhost:8080/login?userid=apple&userpw=1111
app.get('/login', (req, res) => {
console.log('login 호출!')
console.log('path: ', req.path);
console.log('query:', req.query);
res.sendStatus(200);
});
app.post('/login', (req, res) => {
console.log('login 호출!');
console.log(req.body);
res.status(200).send('로그인 되었습니다!')
});
app.listen(8080);
route()
- 특정 URL에 대한 미들웨어 및 라우팅 로직을 모듈화하고 그룹화할 수 있음
- 가독성을 향상시키고 유지 보수를 용이하게 함
- route() 메서드는 Router 객체를 반환. 해당 객체로 특정 URL 경로에 대한 라우팅을 설정
import express from 'express';
const app = express();
app
.route('/posts')
.get((req, res) => {
res.status(200).send('GET: /posts');
})
.post((req, res) => {
res.status(200).send('POST: /posts');
});
app
.route('/member/:id')
.put((req, res) => {
res.status(201).send('PUT: /member/:id')
})
.delete((req, res) => {
res.status(200).send('DELETE: /member/:id');
});
app.listen(8080);
morgan
- http 요청에 대한 로깅을 수행하기 위한 미들웨어
- express와 함꼐 사용되며 클라이언트로부터 오는 각각의 요청에 대한 정보를 로깅
- 요청 HTTP 메서드, 발생한 URL, IP주소, 응답상태코드. 데이터의 크기를 알 수 있음
- 옵션: common, short, tiny, dev, combined
'코딩 > Web' 카테고리의 다른 글
React (1) | 2024.06.07 |
---|---|
node.js 동기, 비동기 (0) | 2024.04.26 |
node.js (1) | 2024.04.26 |
자바스크립트 정규 표현식, 이벤트 (0) | 2024.04.18 |
자바스크립트 객체 (0) | 2024.04.17 |