Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to append binary data to a buffer in node.js
    text
    copied!<p>I have a buffer with some binary data:</p> <pre><code>var b = new Buffer ([0x00, 0x01, 0x02]); </code></pre> <p>and I want to append <code>0x03</code>.</p> <p>How can I append more binary data? I'm searching in the documentation but for appending data it must be a string, if not, an error occurs (<em>TypeError: Argument must be a string</em>):</p> <pre><code>var b = new Buffer (256); b.write ("hola"); console.log (b.toString ("utf8", 0, 4)); //hola b.write (", adios", 4); console.log (b.toString ("utf8", 0, 11)); //hola, adios </code></pre> <p>Then, the only solution I can see here is to create a new buffer for every appended binary data and copy it to the major buffer with the correct offset:</p> <pre><code>var b = new Buffer (4); //4 for having a nice printed buffer, but the size will be 16KB new Buffer ([0x00, 0x01, 0x02]).copy (b); console.log (b); //&lt;Buffer 00 01 02 00&gt; new Buffer ([0x03]).copy (b, 3); console.log (b); //&lt;Buffer 00 01 02 03&gt; </code></pre> <p>But this seems a bit inefficient because I have to instantiate a new buffer for every append.</p> <p>Do you know a better way for appending binary data?</p> <p><strong>EDIT</strong></p> <p>I've written a <a href="https://github.com/Gagle/Node-BufferedWriter" rel="nofollow noreferrer">BufferedWriter</a> that writes bytes to a file using internal buffers. Same as <a href="https://github.com/Gagle/Node-BufferedReader" rel="nofollow noreferrer">BufferedReader</a> but for writing.</p> <p>A quick example:</p> <pre><code>//The BufferedWriter truncates the file because append == false new BufferedWriter ("file") .on ("error", function (error){ console.log (error); }) //From the beginning of the file: .write ([0x00, 0x01, 0x02], 0, 3) //Writes 0x00, 0x01, 0x02 .write (new Buffer ([0x03, 0x04]), 1, 1) //Writes 0x04 .write (0x05) //Writes 0x05 .close (); //Closes the writer. A flush is implicitly done. //The BufferedWriter appends content to the end of the file because append == true new BufferedWriter ("file", true) .on ("error", function (error){ console.log (error); }) //From the end of the file: .write (0xFF) //Writes 0xFF .close (); //Closes the writer. A flush is implicitly done. //The file contains: 0x00, 0x01, 0x02, 0x04, 0x05, 0xFF </code></pre> <p><strong>LAST UPDATE</strong></p> <p>Use <a href="http://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength" rel="nofollow noreferrer">concat</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload