Node

이미지나 음악파일을 보여지게하기(fs.readFile)

jennyiscoding 2022. 7. 3. 13:55

localhost:3000을 통해 접속하면 사진이 나오고 4000을통해 접속하면 노래가 나오도록 해보자.  

코드 : 

const http = require('http');
const fs = require('fs');

http.createServer((req,resp)=>{
    fs.readFile('./tesst.jpg',(err,data)=>{
        if(err){
            console.log(err);
        }else{
            resp.writeHead(200,{'content-type':'image/jpg'})
            resp.end(data);

        }
    })
}).listen(3000,()=>{
    console.log('3000번 포트로 이미지 서버 실행중..')
})


//yout.com에서 유튜브 노래 다운받음!
http.createServer((req,resp)=>{
    fs.readFile('./anysong.mp3',(err,data)=>{
        if(err){
            console.log(err);
        }else{
            resp.writeHead(200,{'content-type':'audio/mp3'})
            resp.end(data);
        }
    })
}).listen(4000,()=>{
    console.log('4000번 포트로 오디오 서버 실행중..');
})

node 7_http3.js를 통해 실행하면 3000번과 4000번이 동시에 실행된다. 

localhost:3000을 통해 접속하면 사진이 보인다. 

localhost:4000으로 접속하면 아래와 같이 mp3가 보이게 된다.