(closed) nodejs responding an image (via pipe and response.end()) leads into strange behaviour

Posted by johannesboyne on Stack Overflow See other posts from Stack Overflow or by johannesboyne
Published on 2012-07-11T07:49:51Z Indexed on 2012/07/11 9:15 UTC
Read the original article Hit count: 130

Filed under:
|

What the Problem was:

I had 2 different writeStreams! If WriteStram#1 is closed, the second should be closed too and then it all should be piped...

BUT node is asynchronious so while one has been closed, the other one hasn't. Even the stream.end() was called... well you always should wait for the close event!

thx guys for your help!


I am at my wit's end.

I used this code to pipe an image to my clients:

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

it does work but sometimes the image is not transferred completely. But no error is thrown neither on client side (browser) nor on server side (node.js).

My second try 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 behaviour...

Does anyone got a clue for me?

Regards!

(abstracted 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 just creates a new file, saves it to the disk and gives back the path (link)

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about node.js