title: How to close file handle with promises?
body: <p>I'm trying to use the <code>canvas</code> module to create a PNG file in a node.js script.</p>
  
  <p>I have a file, <code>image.js</code> that handles the image creation:</p>
  
  <pre><code>const { createCanvas, loadImage } = require('canvas');
  const fs = require('fs');
  
  function generateImage(param1, param2) {
    const canvas = createCanvas(4096, 4096);
    const ctx = canvas.getContext('2d');
    // ...
    return new Promise(function (resolve, reject) {
      loadImage('base.png').then((image) =&gt; {
        ctx.drawImage(image, 40, 40, 200, 200);
  
        let out = fs.createWriteStream(__dirname + '/temp.png');
        let stream = canvas.pngStream();
  
        stream.on('data', function (chunk) {
          out.write(chunk);
        });
  
        stream.on('end', function () {
          console.log('saved png');
          out.close(); // i probably don't need both, but neither seems to work properly...
          out.end();
          resolve();
        });
      });
    });
  }
  
  module.exports = generateImage;
  </code></pre>
  
  <p>When I append <code>generateImage('a', 'b');</code> at the end of this file and then run it separately (<code>node image.js</code>), it works as expected and produces my image. However, when I try to call it from a different file (in the same folder), it seems like the file handle does not close, and the image on disk is an empty file while the script is running.</p>
  
  <p><code>main.js</code> (simplified):</p>
  
  <pre><code>const generateImage = require('./image');
  const fs = require('fs');
  
  async function main() {
      var stats = fs.statSync("temp.png");
      console.log(stats["size"]); // output: 0, expected: &gt; 0
  }
  
  generateImage("text", "text").then(() =&gt; main());
  </code></pre>
  
  <p>I'm new to node.js, so it's very possible that I'm missing something obvious.</p>