title: Trouble reading and writing binary data with Node.js
body: <p>looking for some newb NodeJS help.  There HAS to be something simple I'm overlooking, but I've tried to go about this several ways and continuously end up with odd results.</p>
  
  <p>I took the majority of the following code from <strong><a href="https://stackoverflow.com/questions/5985748/node-js-fs-read-example">this question</a></strong>.</p>
  
  <pre><code>// 128Kb Chunks
  var targetSize = 131072;
  
  // Open the file
  fs.open('/project/input.png', 'r', function(err, fd) {
  
      // Gather some info about the file
      fs.fstat(fd, function(err, stats) {
          var bufferSize=stats.size,
              chunkSize=targetSize,
              buffer=new Buffer(bufferSize),
              bytesRead = 0,
              isFinal = false;
  
          while (bytesRead &lt; bufferSize) {
  
              if ((bytesRead + chunkSize) &gt; bufferSize) {
                  chunkSize = (bufferSize - bytesRead);
                  isFinal = true;
              } else {
                  isFinal = false;
              }
  
              fs.read(fd, buffer, bytesRead, chunkSize, bytesRead);
  
              bytesRead += chunkSize;
  
              if( isFinal ) {
                  fs.writeFileSync("/project/output.png", buffer);
              }
  
          }
  
      });
  
      // Done
      fs.close(fd);
  
  });
  </code></pre>
  
  <p>When I output the output.png file, which has an identical file size as my input (so something must be sorta working?), my image viewer cannot read the file, so it is corrupted in some way.</p>
  
  <p>I tried to keep this question and example as simple as possible, but in case it matters or prompts further advice, here are my core goals:</p>
  
  <ul>
  <li>Read a file in fixed chunk sizes (128KB)</li>
  <li>Encrypt and store each chunk in mongodb (intentionally excluded here)</li>
  <li>Be able to reassemble the image later on</li>
  </ul>
  
  <p>I appreciate any help you can give.</p>
  
  <hr>
  
  <p><strong>Update:</strong>
  Found the answer, and it was simple as expected.</p>
  
  <p>The code I copied had a small bug, namely the fs.close() </p>
  
  <p>The stream was being closed before it was being read.</p>
  
  <p>This was also visible when I added a callback to my fs.read, which has a 'err' first param:</p>
  
  <pre><code>[Error: EBADF, read] errno: 9, code: 'EBADF'
  </code></pre>