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)
I've used this before and all that is needed is that in the function (req, res) {
:
var path = ...;
res.writeHead(200, {
'Content-Type' : 'image/png'
});
fs.createReadStream(path).pipe(res);
where path
is the computed path to the file to send. .pipe()
will transfer the data from the read stream to the write stream and call end when the read stream ends, so there is no need to use res.end()
after.
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!