3

I am using the node-png library to make the png and then save it in the local directory but when I go to open it back up, it says that it does not exist. I want to either read in the data and send it out or just have the response send an <img> field with the picture. Here's what I have so far:

//write out img data
png.pack().pipe(dst);

//link to new image made
var link = fs.createReadStream('out.png'); //says that this does not exist

//write out response with img then delete file
response.writeHead(200, {"Content-Type": "image/png"});
response.end(link, 'binary');
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
CRS
  • 827
  • 2
  • 13
  • 20
  • Does `dst` have an optional callback for when it finished writing to the disk? – Jason Aller Apr 16 '14 at 20:03
  • no, there is only one other option that can be set with it [link](http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options) – CRS Apr 16 '14 at 20:07
  • You can always wait for the stream to end before doing anything. The [event-stream](https://github.com/dominictarr/event-stream) module has the `through` method that can do this. – tadman Apr 16 '14 at 20:10
  • @CRS have you looked into using the end option: `reader.pipe(writer, { end: false });` followed by `reader.on('end', function() {writer.end('Goodbye\n');});` which looks like it would behave similar to a callback? – Jason Aller Apr 16 '14 at 20:15

1 Answers1

2

Couldnt you just skip writing to file altogether?

var output = png.pack();
res.setHeader('Content-Type', 'image/png');
output.pipe(res);

If you do need to write it to disk simultaneously, refer to this answer:

https://stackoverflow.com/a/19561718/944006

If you need to write to disk FIRST and THEN read from that, you would do:

var output = png.pack();
output.pipe(dst, { end: false });
output.on('end', function(){
     //Read your file and set your response here.
}

I didn't test any of this but that's the way piping works in general.

Community
  • 1
  • 1
Thad Blankenship
  • 2,242
  • 3
  • 16
  • 16