我在处理 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 可能提供更好的用户体验,这种假设是否正确?感觉好像不那么像块状物; 这是真的吗?是否还有其他的优点、缺点、注意事项或陷阱我需要知道?