Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- LifeCycle
- GraphQL
- winston
- nestjs
- REST API
- 알고리즘
- MySQL
- 인접행렬
- Deep Dive
- Linux
- javascript
- JWT
- bean
- 프로그래머스
- OOP
- html
- Kubernetes
- 탐욕법
- node.js
- 코딩테스트
- puppeteer
- dfs
- 인접리스트
- Interceptor
- typescript
- TIL
- Spring
- java
- css
- 자료구조
Archives
- Today
- Total
처음부터 차근차근
Node.js 파일 읽기 구현 본문
728x90
Node.js 파일 다루는 방법
- 정보를 다루는 핵심적인 처리 4가지로
CURD : Create, Read, Update, Delete
이렇게 존재한다.
먼저 Node.js file read로 검색하면, 공식문서를 통해 사용법을 익힐 수 있다.
var fs = require('fs');
fs.readFile('sample.txt', 'utf8', function(err, data){
console.log(data);
});
https://nodejs.dev/en/learn/reading-files-with-nodejs/
Reading files with Node.js
How to read files using Node.js
nodejs.dev
파일을 이용한 본문 구현
- 쿼리스트링에 따라 본문이 변경되는 웹 어플리케이션을 만들어보자.
data라는 폴더 만들고 그 안에 각각 HTML, CSS, JavaScript라는 이름의 파일들을 만들어서 p태그 내부의 본문들을 각각의 파일들에 넣어주자.
var http = require('http');
var fs = require('fs');
var url = require('url');
var app = http.createServer(function(request,response){
var _url = request.url;
var queryData = url.parse(_url, true).query;
var title = queryData.id;
console.log(title);
if(_url == '/'){
title = 'Welcome';
}
if(_url == '/favicon.ico'){
return response.writeHead(404);
}
response.writeHead(200);
fs.readFile(`data/${queryData.id}`, 'utf-8', (err, description) => {
const template = `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
<ul>
<li><a href="/?id=HTML">HTML</a></li>
<li><a href="/?id=CSS">CSS</a></li>
<li><a href="/?id=JavaScript">JavaScript</a></li>
</ul>
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>
`;
response.end(template);
});
});
app.listen(3000);
'FrameWork > Node.js' 카테고리의 다른 글
Node.js 파일 리스트 읽어오기 (0) | 2023.05.30 |
---|---|
Node.js 홈페이지 구현 (0) | 2023.05.30 |
Node.js Not found 구현 (0) | 2023.05.30 |
Node.js - URL의 이해 (0) | 2023.05.30 |
Node.js의 등장과 웹서버 만들기 (0) | 2023.05.30 |