4

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.

4

3 に答える 3

7

呼び出しは適切な場所にありますが、データを読み取りストリームから書き込みストリームに転送するだけres.writeHead()なので、イベント リスナーを に置き換えることができます。また、HTTP 応答コードは適切ではないようです。file.pipe(res);res202200

var file = fs.createReadStream(image);
res.writeHead(200, {"Content-Type" : "image/png"});
file.pipe(res);
于 2012-11-21T04:19:37.943 に答える
5
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);
于 2012-11-21T04:24:48.540 に答える
1

@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);
        };
    });
于 2012-11-21T19:33:56.157 に答える