我正在使用 node.js 进行一些操作,发现了两种读取文件并将其发送到网络的方法。在确保文件存在并使用 writeHead 发送正确的 MIME 类型后:
// read the entire file into memory and then spit it out
fs.readFile(filename, function(err, data){
if (err) throw err;
response.write(data, 'utf8');
response.end();
});
// read and pass the file as a stream of chunks
fs.createReadStream(filename, {
'flags': 'r',
'encoding': 'binary',
'mode': 0666,
'bufferSize': 4 * 1024
}).addListener( "data", function(chunk) {
response.write(chunk, 'binary');
}).addListener( "close",function() {
response.end();
});
如果涉及到大文件,比如视频,使用fs.createReadStream是否会提供更好的用户体验呢?感觉它可能会减少阻塞,这是真的吗?还有其他的优点、缺点、警告或需要了解的问题吗?