BaHaa Jr.
BaHaa Jr.

Reputation: 534

Node.js on('end') stream's listener fires twice

It's a ordinary node practice, the on("end") callback fires twice per request even with using readable.once("end"). Here's tha code:

require("http").createServer(function (req, res) {
     var readable = require("fs").createReadStream("./image.jpg",{highWaterMark:1024*1024});
     readable.on("data", function (data) {
         res.write(data);
     })

    readable.on("end", function () {
        res.end()
        console.log("Ended");
    })

}).listen(9000, function () {
    console.log("Listening.... on 9000");
});

Upvotes: 2

Views: 760

Answers (1)

Mohamed Salem
Mohamed Salem

Reputation: 46

There are 2 requests being sent whenever you request the page one for the main directory " / " and the other for the "favicon.ico" , so that why the function fires twice, in order to solve that put an if condition for the req.url and spacify the directory you want and it will work.

Upvotes: 3

Related Questions