Node.js 클라이언트에 파일 보내기

Shraddha Paghdar 2023년10월12일
Node.js 클라이언트에 파일 보내기

이 기사에서는 Express를 사용하여 Node.js의 클라이언트에 파일을 보내는 방법에 대해 알아봅니다.

Express를 사용하여 Node.js에서 파일 보내기

Express.js 또는 Express는 Node.js용 백엔드 웹 유틸리티 프레임워크입니다. Express는 웹 및 모바일 애플리케이션을 위한 강력한 특성 세트를 제공하는 Node.js 웹 애플리케이션 프레임워크입니다.

res.sendFile() 함수는 지정된 경로의 파일을 전달하고 파일 이름 확장자를 기반으로 content-type 응답에 대한 HTTP 헤더 필드를 설정합니다.

통사론:

res.sendFile(path[, options][, fn])
매개변수 설명
path 전송해야 하는 파일의 경로를 설명하는 필수 매개변수입니다.
options 전송되는 파일의 maxAge, root 등과 같은 다양한 속성을 포함하는 선택적 매개변수입니다.
fn 파일이 호출될 때 호출되는 콜백 함수입니다.

클라이언트에 파일을 전송하려면 아래 지침을 따르십시오.

  1. 익스프레스 패키지를 설치합니다.

    $ npm install express
    
  2. index.js 파일을 생성하고 아래 명령을 실행합니다.

    node index.js
    
  3. helloworld.txt 파일을 생성합니다.

    Hello World!
    
  4. 아래 코드 조각을 전달하여 index.js 파일을 실행합니다.

전체 소스 코드 - index.js:

const express = require('express');
const app = express();
const path = require('path');
const PORT = 3001;

app.get('/', (req, res, next) => {
  const fileName = 'helloworld.txt';
  res.sendFile(fileName, {root: path.join(__dirname)}, (err) => {
    if (err) {
      next(err);
    } else {
      console.log('File Sent:', fileName);
    }
  });
});

app.listen(PORT, (err) => {
  if (err) console.log(err);
  console.log('Server listening on PORT', PORT);
});

위의 예에서는 지정된 포트 3001에서 수신 대기하는 서버를 만들었습니다. 서버가 지정된 포트를 수신하면 일치하는 첫 번째 경로 내에서 코드를 실행합니다.

응답 개체는 sendFile() 메서드를 사용하여 클라이언트에 반환됩니다. 오류가 발생하면 next() 메서드를 사용하여 오류를 오류 처리기로 전달합니다.

모든 것이 원활하면 파일 내용과 함께 응답 개체를 클라이언트에 반환합니다.

Node.js를 지원하는 replit에서 위 코드를 실행하면 아래와 같은 결과가 표시됩니다.

출력:

Server listening on PORT 3001
File Sent: helloworld.txt

Express를 사용하여 Node.js에서 파일 보내기

코드 데모 실행

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn