title: Pass Byte Array as std::vector<char> from Node.js to C++ Addon
body: <p>I have some constraints where the addon is built with nan.h and v8 (not the new node-addon-api).</p>
  
  <p>The end function is a part of a library. It accepts <code>std::vector&lt;char&gt;</code> that represents the bytes of an image.</p>
  
  <p>I tried creating an image buffer from Node.js:</p>
  
  <pre class="lang-js prettyprint-override"><code>const img = fs.readFileSync('./myImage.png');
  myAddonFunction(Buffer.from(img));
  </code></pre>
  
  <p>I am not really sure how to continue from here. I tried creating a new vector with a buffer, like so:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>std::vector&lt;char&gt; buffer(data);
  </code></pre>
  
  <p>But it seems like I need to give it a size, which I am unsure how to get. Regardless, even when I use the initial buffer size (from Node.js), the image fails to go through.</p>
  
  <pre><code>terminate called after throwing an instance of 'std::bad_alloc'
    what():  std::bad_alloc
  [1]    16021 abort (core dumped)
  </code></pre>
  
  <p>However, when I read the image directly from C++, it all works fine:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>std::ifstream ifs ("./myImage.png", std::ios::binary|std::ios::ate);
  std::ifstream::pos_type pos = ifs.tellg();
  std::vector&lt;char&gt;  buffer(pos);
  ifs.seekg(0, std::ios::beg);
  ifs.read(&amp;buffer[0], pos);
  
  // further below, I pass "buffer" to the function and it works just fine. 
  </code></pre>
  
  <p>But of course, I need the image to come from Node.js. Maybe Buffer is not what I am looking for?</p>