Marc Rasmussen
Marc Rasmussen

Reputation: 20565

node.js stream header range is undefined

i am creating a streaming module that will stream any file on my server to the user

for this i have the following node code:

    .get(function (req, res) {
        if (req.query.resourceToken) {
        var decoded = jwt.decode(req.query.resourceToken, require('../secret')());
        var mediaObject = decoded.mediaObject;
        var file = path.resolve(mediaObject.targetDir, mediaObject.file.originalname);
        fs.stat(file, function (err, stats) {
            if (err) {
                if (err.code === 'ENOENT') {
                    // 404 Error if file not found
                    return res.sendStatus(404);
                }
                res.end(err);
            }
            var range = req.headers.range;
            if (!range) {
                // 416 Wrong range
                return res.sendStatus(416);
            }
            var positions = range.replace(/bytes=/, "").split("-");
            var start = parseInt(positions[0], 10);
            var total = stats.size;
            var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
            var chunksize = (end - start) + 1;
            res.writeHead(206, {
                "Content-Range": "bytes " + start + "-" + end + "/" + total,
                "Accept-Ranges": "bytes",
                "Content-Length": chunksize,
                "Content-Type": mediaObject.file.mimetype
            });

            var stream = fs.createReadStream(file, {start: start, end: end})
                .on("open", function () {
                    stream.pipe(res);
                }).on("error", function (err) {
                    res.end(err);
                });
        });
    }
    else {
        res.status(500).send('Missing resource token!');
    }
});

Now to download a simple document i have the follow html tag:

<a target="_self" href="http://localhost:433/resource?resourceToken=token" class="btn btn-default">                               <i class="fa fa-download"> </i></a>

Now when i press the button it correctly calls the method however the header range is undefined.

which means it sends the error code 416 (as shown in the above code).

Can anyone tell me why this is happening and what im missing?

Upvotes: 1

Views: 1201

Answers (1)

robertklep
robertklep

Reputation: 203534

Range requests serve a rather specific purpose (like enabling partial downloads during audio/video scrubbing).

Your HTML suggests that you just want to present a download link for a particular resource, and the browser won't issue a range request for that (or it might, but only after the initial request).

So your code should allow for the Range header to not exist.

Upvotes: 1

Related Questions