title: NodeJS splitting buffer by delimter
body: <p>I have a basic TCP server in NodeJS which receives JSON strings. These can be multiple strings at a time (delimited by <code>\n</code>) or single strings.</p>
  
  <p>The problem arises when i receive multiple ones that are delimited by <code>\n</code>.</p>
  
  <p>What I'm trying to do is split the buffer data into an array and then loop over that array to avoid JSON parsing errors.</p>
  
  <p>Here is my current code:</p>
  
  <pre><code>var socketServer = net.createServer(function (socket) {
  
          // Handle incoming messages from agents.
          socket.on('data', function (data) {
  
                  // Split the buffer so we dont get JSON parsing errors
                  // Delimiter is \n
                  var splitData = splitBuffer(data, "0x5c6e");
  
                  for (var i = 0; i &lt; splitData.length; i++) {
  
                      // Error arises here since there are multiple JSONs in the string
                      console.log(JSON.parse(splitData[i]));
  
                  }
  
          });
  
  
  });
  
  function splitBuffer(buf, delimiter) {
    var arr = [], p = 0;
  
    for (var i = 0, l = buf.length; i &lt; l; i++) {
      if (buf[i] !== delimiter) continue;
      if (i === 0) {
        p = 1;
        continue; // skip if it's at the start of buffer
      }
      arr.push(buf.slice(p, i));
      p = i + 1;
    }
  
    // add final part
    if (p &lt; l) {
      arr.push(buf.slice(p, l));
    }
  
    return arr;
  }
  </code></pre>
  
  <p>For some reason the <code>splitBuffer()</code> function is unable to split the buffer according to my delimiter.</p>
  
  <p>Any ideas what I'm doing wrong here? </p>