Responding to an image (via pipe and response.end ()) leads to strange behavior

I used this code to transfer the image to my clients:

req.pipe(fs.createReadStream(__dirname+'/imgen/cached_images/' + link).pipe(res)) 

It does work , but sometimes the image is not completely transmitted. But no error occurs neither on the client side (browser), nor on the server side (node.js).

My second attempt was

 var img = fs.readFileSync(__dirname+'/imgen/cached_images/' + link); res.writeHead(200, { 'Content-Type' : 'image/png' }); res.end(img, 'binary'); 

but it leads to the same strange behavior ...

Has anyone got a key for me?

(abstract code ...)

 var http = require('http'); http.createServer(function (req, res) { Imgen.generateNew( 'virtualtwins/www_leonardocampus_de/overview/28', 'www.leonardocampus.de', 'overview', '28', null, [], [], function (link) { fs.stat(__dirname+'/imgen/cached_images/' + link, function(err, file_info) { if (err) { console.log('err', err); } console.log('file info', file_info.size); res.writeHead(200, 'image/png'); fs.createReadStream(__dirname+'/imgen/cached_images/' + link).pipe(res); }); } ); }).listen(13337, '127.0.0.1'); 

Imgen.generateNew simply creates a new file, saves it to disk and returns the path (link).

+4
source share
2 answers

What is the problem: I had 2 different recording scripts! If WriteStream # 1 is closed, the second must also be closed, and then everything must be connected to the network.

But node is asynchronous, so when one of them is closed, the other is not. Even stream.end () was called ... well, you should always wait for the close event!

+2
source

I have used this before, and all that is needed is that in function (req, res) { :

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

where path is the calculated path to the file to send. .pipe() will transfer data from the read stream to the write stream and end the call when the read stream ends, so there is no need to use res.end() after.

+2
source

All Articles