[NodeJS] nodejs 그림 불러오기
html src
보통 그림을 가져올 때, html 파일에서 src 태그를 이용해 그림을 불러온다.
파일구조가 위와 같을 때, index.html 파일 기준으로 그림 파일은 './picture/picture.PNG' 경로를 갖게된다. 그렇다면 아래와 같은 html 코드로 불러올 수 있다.
그림이 나타나지 않는다.
위의 그림은 크롬의 개발자 도구의 Source탭에 나타나는 코드이다.
나타나지 않는 이유는, 서버에 picture.PNG가 없기 때문이다. 무슨 얘기냐면, 저 코드로 picture.PNG를 불러오기 위해서는 url로 접근이 가능해야 한다. 예를 들어 localhost:3000/picture/picture.PNG로 접속했을 때, 해당 그림 파일이 표시되어야 한다. 지금은 그림을 올린 서버가 없다고 가정하고 해결방법을 제시해 본다.
요청에 따른 그림파일 응답
- main.js
var http = require('http');
var fs = require('fs');
var app = http.createServer(function(request, response){
console.log(request.url);
if(request.url ==='/'){
response.writeHead(200);
response.end(fs.readFileSync(__dirname + '\\index.html'));
}
});
app.listen(3000);
위의 index.html파일과 main.js파일을 위에서 언급한 디렉토리 구조 상태에서, main.js를 node로 구동시킨 후, localhost:3000으로 접속했을 때의 로그는 아래와 같다. (7번째 줄의 console.log의 결과이다.)
localhost:3000으로 접속했을 때, 요청으로 들어오는 url이 '/' 이고, src 태그를 만나서 <img src>에 입력한 경로대로 다시 요청이 들어오는 것을 확인할 수 있다. 그렇다면 이 요청에 따라서 그림파일을 읽어서 client에 쏴주면(?) 될것 같다. main.js와 index.html 모두 손보자.
- main.js
var http = require('http');
var fs = require('fs');
var app = http.createServer(function(request, response){
console.log(request.url);
if(request.url ==='/'){
response.writeHead(200);
response.end(fs.readFileSync(__dirname + '\\index.html'));
}
if(request.url==='/picture'){
fs.readFile('./picture/picture.PNG', function(err, data){
console.log('picture loading...');
response.writeHead(200);
response.write(data);
response.end();
});
}
});
app.listen(3000);
- index.html
<!DOCTYPE html>
<head>
<title>my test</title>
</head>
<body>
<h1>test page</h1>
<img src="/picture" width="200px">
</body>
</html>
index.html 파일의 <img src> 요청 경로를 간단하게 '/picture'로 수정하였다. 그러면 요청 url로 '/picture'가 들어올 것이고, 그러면 fs.readFile을 이용해 그림 파일을 읽은 뒤 읽은 그림을 client로 전송하도록 구성하였다. 로그는 아래와 같다.
/favicon.ico는 일단 무시하도록 하자.
'/'경로 요청이 들어온 뒤, '/picture'경로 요청이 들어오는 것을 확인할 수 있다.
- 페이지 접속 결과
그림이 출력되는것을 확인할 수 있다.