title: How to convert a hex string to base64 for image saving in NodeJS
body: <p>I'm making a NodeJS sockets.io multiplayer drawing canvas. The data gets saved as color id's in a 2D matrix, and I have an array of color hex codes to match with the id's.</p>
  
  <p>I need to be able to save the image as a file, and so I got to the point of storing the image data as a continuous string, joining every pixel's hex code:</p>
  
  <pre><code>// 'boardData' contains the index of the color for each pixel
  // 'colors' is an array on hex values
  
  var hexString = ""
  
  for (var x = 0; x &lt; boardWidth; x++) {
      for (var y = 0; y &lt; boardHeight; y++) {
          hexString += colors[boardData[x][y]].replace('#','');
      }
  }
  </code></pre>
  
  <p>The result is something like <code>ffffff3fbae52dffba...</code></p>
  
  <p>I managed to convert this string into base64 by doing the following:</p>
  
  <pre><code>var base64Data = Buffer.from(hexString, 'hex').toString('base64')
  </code></pre>
  
  <p>Then, I tried saving it by doing this:</p>
  
  <pre><code>fs.writeFile("image.png", base64Data, {encoding: 'base64'}, function(err) {
      if (err) return err;
      console.log('Saved!');
  });
  </code></pre>
  
  <p>But the resulting images seem to have an incompatible format.</p>
  
  <p>When I try saving a 16x16 completely white image, the base64 code comes out as <code>///////////////////////////...</code>, but when I try online image converters, a 16x16 white image becomes <code>iVBORw0KGgoAAAANSUhEUgAAAAg...</code>, and hardcoding this into the fs.writeFile data works just fine. Actually, seems like even a 1x1 white image yields a lot of characters, so I'm not entirely sure how this even works.</p>
  
  <p>I believe I'm missing a step here. Can someone point me in the right direction? Is there maybe another way of converting this raw color data into an image file?</p>