问题是我找不到如何停止刷新文件数据。我尝试了unpipe()
方法。从curl请求文件然后关闭它似乎工作。但它在关闭浏览器时不会停止刷新文件。并读取整个文件。我怎么能阻止它?
var http = require("http"),
fs = require("fs"),
url = require("url");
var stream;
var requestHandlers = {
video: function(request, response) {
var totalbytes = 0;
response.writeHead(200, {"Content-Type": "video/mp4"});
stream = fs.createReadStream('video.mp4');
stream.pipe(response);
stream.on('data', function(chunk) {
totalbytes += chunk.length;
});
stream.on('end', function(){
console.log("Video connection ended. Total bytes sent %d", totalbytes);
});
stream.on('close', function(){
console.log("Video connection closed. Total bytes sent %d", totalbytes);
});
}
}
var handle = {
"/video.mp4": requestHandlers.video
};
var myServer = http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received from " + request.connection.remoteAddress);
if (typeof handle[pathname] === 'function') {
handle[pathname](request, response);
} else {
response.writeHead(404, {"Content-Type": "text/html"});
response.write("404 Not found");
response.end();
}
request.on('close', function(){
// stream.unpipe(); //does not help
console.log("Connection closed");
});
});
myServer.listen(5555);
console.log("Server started");