Home  >  Article  >  Web Front-end  >  How to read large files in nodejs

How to read large files in nodejs

亚连
亚连Original
2018-06-21 17:04:302250browse

This article mainly introduces nodejs to read large files in detail, such as online videos, which has certain reference value. Interested friends can refer to

nodejs for video reading. It cannot be read in one go like reading pictures, but must read part of it and return part of it, so that the client can play while buffering, without having to wait for all buffering to be completed before playing.

Old rules, directly paste the code to explain:

var fs = require('fs'); 

function readBigFileEntry(filename, response) { 
path.exists(filename, function(exists) { 
if (!filename || !exists) { 
response.writeHead(404); 
response.end(); 
return; 
} 

var readStream = fs.ReadStream(filename); 

var contentType = 'none'; 
var ext = path.extname(filename); 
switch (ext) { 
case ".flv": 
contentType = "video/flv"; 
break; 
} 

response.writeHead(200, { 
'Content-Type' : contentType, 
'Accept-Ranges' : 'bytes', 
'Server' : 'Microsoft-IIS/7.5', 
'X-Powered-By' : 'ASP.NET' 
}); 



readStream.on('close', function() { 
response.end(); 
console.log("Stream finished."); 
}); 
readStream.pipe(response); 
}); 
}

Get the video stream through the ReadStream method of the fs module, and then bind the closing event: end the response request when the stream reads to the end , and finally read small blocks through the pipe method. The Content-Length attribute cannot be added to the head information here because it must be read in segments. If this attribute is added, the browser will think that the request is over and close the request.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement circular advertising banners in javascript

How to use the swiper component to implement image switching in WeChat Mini Programs Display

How to implement circular advertising banners in javascript

In Vue, the debugging tool vue-devtools (detailed tutorial)

How to implement integrated Iframe page using Vue

The above is the detailed content of How to read large files in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn