안녕하세요. node.js에서 클라이언트로 파일을 보내려고했습니다. 내 코드는 클라이언트가 지정된 URL (/helloworld/hello.js/test)로 이동하면 파일을 스트리밍합니다. Google 크롬에서 파일에 액세스하면 플레이어에서 파일 (.mp3)이 재생됩니다.Node.js가 클라이언트에 파일 보내기
제 목표는 클라이언트의 브라우저에서 파일을 다운로드하고 클라이언트에 저장할 위치를 물어보고 웹 사이트에 스트리밍하지 말라는 것입니다.
http.createServer(function (req, res) {
switch(req.url) {
case '/helloworld/hello.js/test':
var filePath = path.join(__dirname, '/files/output.mp3');
var stat = fileSystem.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.on('open', function() {
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(res);
});
readStream.on('error', function(err) {
res.end(err);
});
고마워요. 작동했지만 지금은 약 4MB의 파일 만 다운로드 할 수 있습니다. 전체 파일 크기는 약 6MB입니다. –
파일 내용을 확인 했습니까? 모든 것이 안에 있습니까? –
Node.js가 단일 스레드이기 때문에 요청 처리기에서'readFileSync' 사용자에게 매우 나쁜 것입니다. 따라서 해당 URL에 두 개의 요청이있는 경우 두 번째 요청은 첫 번째 작업이 완료 될 때까지 기다립니다. localhost에서는 아무 문제가 없다는 것을 알지 못하지만 초당 1,000 건의 요청이있는 프로덕션 서버에서는 지연이 발생합니다. ['readFile'] (http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback)을 대신 콜백으로 사용하십시오 – Curious