Mario
Mario

Reputation: 2031

createReadStream send file http

I'm trying to open an img file and send it through http. I have read that the best method for doing it is creatReadStream because it's async and better for performance.

Here it's my code:

var file = fs.createReadStream(image);

    file.on("error", function(err){
        ...
    });

    res.writeHead(200, {"Content-Type" : "image/png"});

    file.on("data", function(data) {
        res.write(data);
    })

    file.on("end", function() {
        res.end();
    })

How can I know the file size to let res know in order to send it in the headers?

I don't like having writehead not in a callback, what can I do?

Thank you.

Upvotes: 5

Views: 13490

Answers (3)

Mario
Mario

Reputation: 2031

@wayne Thank you so much for your answer but wouldn't be better to use stat asynchronously?

var stat = fs.stat(image, function(err,stats) {
        if (err) {
            req_error(res,err);
        } else {
            res.writeHead(200, {
            'Content-Type' : 'image/png',
            'Content-Length': stats.size
            });

            var file = fs.createReadStream(image);
            file.pipe(res);
        };
    });

Upvotes: 1

wayne
wayne

Reputation: 3410

var stat = fs.statSync('path/to/imagefile');
response.writeHead(200, {
  'Content-Type' : 'image/png',
  'Content-Length': stat.size
});
fs.createReadStream('path/to/imagefile').pipe(response);

Upvotes: 8

Dan D.
Dan D.

Reputation: 74675

The res.writeHead() call is in the right place but the event listeners could be replaced with file.pipe(res); as you are only forwarding the data from the read stream to the write stream of the res. Also the HTTP response code 202 doesn't seem appropriate why not use 200.

var file = fs.createReadStream(image);
res.writeHead(200, {"Content-Type" : "image/png"});
file.pipe(res);

Upvotes: 8

Related Questions