node js를 사용해 http 파일 서버 만들기

이런게 필요한 사람은 pc에 nginX나 iis 등등이 있겠지만

자기 pc가 아닌데 급하게 해야 하는 경우를 위해

node js binary download (official) ->

https://nodejs.org/ko/download

복사해서 파일명.js로 저장 ->

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

const PORT = 8080;

http.createServer((req, res) => {
  const filePath = path.join(process.cwd(), req.url);

  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
      res.end('파일을 찾을 수 없습니다.');
      return;
    }
    // 다운로드 헤더 지정 (항상 첨부파일로 다운로드)
    res.writeHead(200, {
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': `attachment; filename="${path.basename(filePath)}"`
    });
    res.end(data);
  });
}).listen(PORT, () => {
  console.log(`서버가 http://localhost:${PORT} 에서 실행 중입니다.`);
});

실행 ->

"C:\Program Files\nodejs\node.exe" 파일명.js

브라우저 주소창 ->

http://127.0.0.1:8080

Comments

No comments yet. Why don’t you start the discussion?

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다