
eio_sendfile 함수의 콜백 함수 인자 중 'err' 변수는 전송 중 발생한 에러를 나타내며, null이 아닌 경우 에러가 발생한 것을 의미합니다.
'err' 변수가 null인 경우, 전송이 성공적으로 완료된 것입니다.
'err' 변수가 null이 아닌 경우, 전송 중 발생한 에러를 console.error() 함수를 통해 출력할 수 있습니다.
eio_sendfile 함수의 콜백 함수 인자 중 'res' 변수는 전송 결과를 나타내며, 전송이 성공적으로 완료되면 null이 아닌 객체를 반환합니다.
이 객체는 전송한 파일의 정보를 포함하며, 전송한 파일의 이름, 크기, MIME 타입 등을 포함합니다.
eio_sendfile 함수가 비동기적으로 작동하는 이유는 Node.js가 이벤트 루프를 기반으로 동작하기 때문입니다.
Node.js는 요청을 처리하는 동안 다른 요청을 처리할 수 있도록 이벤트 루프를 사용하며, eio_sendfile 함수도 이 이벤트 루프를 기반으로 동작합니다.
이벤트 루프를 사용하면 Node.js가 동시에 여러 요청을 처리할 수 있으며, 전송이 완료되면 콜백 함수가 호출됩니다.
예제 코드는 다음과 같습니다.
#hostingforum.kr
javascript
const express = require('express');
const app = express();
const eio = require('socket.io');
app.get('/file', (req, res) => {
const file = 'example.txt';
const range = req.headers.range;
if (!range) {
res.status(400).send('Please specify the range of the file you want to download.');
return;
}
const fileSize = 1024 * 1024; // file size in bytes
const chunkSize = 10 * 1024 * 1024; // 10MB chunks
const start = parseInt(range.replace(/bytes=/, '').split('-')[0], 10);
const end = Math.min(start + chunkSize, fileSize - 1);
const fileStream = fs.createReadStream(file, { start, end });
const headers = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': end - start + 1,
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="example.txt"; filename*=UTF-8''example.txt`,
};
res.writeHead(206, headers);
fileStream.pipe(res);
});
이 예제 코드는 Express.js와 Socket.IO를 사용하여 파일을 전송하는 예제입니다.
이 예제 코드는 파일의 크기, MIME 타입, 파일 이름 등을 포함한 헤더를 전송하고, 파일의 내용을 전송합니다.
이 예제 코드는 비동기적으로 작동하며, 전송이 완료되면 콜백 함수가 호출됩니다.
이 예제 코드는 Node.js의 이벤트 루프를 기반으로 동작하며, 동시에 여러 요청을 처리할 수 있습니다.
2025-07-31 06:24