웹/(Node.js)노드
(Node.js) 파일 목록 불러오기/ 파일 이름 불러오기 + 예제(간단함)
공부가싫다가도좋아
2021. 9. 8. 10:00
반응형
파일 목록 불러오기/ 파일 이름 불러오기
Node.js에서 파일 목록 불러오기는 매우 쉽습니다.
포스팅 요약
1. 파일 불러오는 형식
2. Node.js로 파일목록 읽어오는 방법
3. fs.readdir 을 사용한 간단한 예제
1. 파일 불러오는 형식
const fs = require("fs");
fs.readdir(파일명, (err, files)=>{
});
2. Node.js로 파일목록 읽어오는 방법
data파일을 생성하고, 파일안에 원하는 이름, 원하는 형식의 파일들을 생성해 줍니다.
저는 그냥 txt파일로 생성했습니다.
파일명: server.js
const http = require("http");
const fs = require("fs");
const app = http.createServer((request, response) => {
const _url = request.url;
const fullUrl = new URL("http://localhost:3000" + _url);
const pathName = fullUrl.pathname;
if (pathName === "/") {
fs.readdir("./data", (err, files) => {
console.log(files);
});
}
});
app.listen(3000, () => {
//포트번호 3000으로 서버 구동
console.log("서버 시작 주소: http:localhost:3000");
});
<결과>
3. fs.readdir 을 사용한 간단한 예제
<현재 디렉토리에 있는 파일들>
파일명: server.js
const http = require("http");
const fs = require("fs");
const app = http.createServer((request, response) => {
const _url = request.url;
const fullUrl = new URL("http://localhost:3000" + _url);
const pathName = fullUrl.pathname;
if (pathName === "/") {
let list = "";
fs.readdir("./data", (err, files) => { //data폴더에 있는 파일모록을 불러옴.
files.forEach((file) => {
list += `<li>${file}</li>`;
});
response.writeHead(200, { "Content-Type": "text/html;charset = utf-8" });
response.end(`<ul>${list}</ul>`);
/* list =
<li>NodeJs</li>
<li>css</li>
<li>html</li>
/*
});
}
});
app.listen(3000, () => {
//포트번호 3000으로 서버 구동
console.log("서버 시작 주소: http:localhost:3000");
});
> 터미널 창에서 node server 입력하여 서버 실행
> localhost:3000 에 접속
<결과>
반응형