Close the readable stream

The problem is, I cannot find how to stop clearing the file data. I tried the method unpipe()

. And it seems like it works when the file is requested from curl and then closes it. But when you close the browser, it doesn't stop flushing the file. And the whole file is read. How can I stop it?

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");

      

+3


source to share





All Articles