Example #1
0
function stringToBuffer(string) {
  var buffer = new Buffer(Buffer.byteLength(string));
  buffer.utf8Write(string);
  return buffer;
}
Example #2
0
assert.throws(function () {
  b.unpack('N', 8);
});

b[4] = 0xDE;
b[5] = 0xAD;
b[6] = 0xBE;
b[7] = 0xEF;

assert.deepEqual([0xDEADBEEF], b.unpack('N', 4));


// Bug regression test
var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語
var buffer = new Buffer(32);
var size = buffer.utf8Write(testValue, 0);
puts('bytes written to buffer: ' + size);
var slice = buffer.toString('utf8', 0, size);
assert.equal(slice, testValue);


// Test triple  slice
var a = new Buffer(8);
for (var i = 0; i < 8; i++) a[i] = i;
var b = a.slice(4,8);
assert.equal(4, b[0]);
assert.equal(5, b[1]);
assert.equal(6, b[2]);
assert.equal(7, b[3]);
var c = b.slice(2 , 4);
assert.equal(6, c[0]);
Example #3
0
Connection.prototype._sendBody = function (channel, body, properties) {
  // Handles 3 cases
  // - body is utf8 string
  // - body is instance of Buffer
  // - body is an object and its JSON representation is sent
  // Does not handle the case for streaming bodies.
  if (typeof(body) == 'string') {
    var length = Buffer.byteLength(body);
    //debug('send message length ' + length);

    sendHeader(this, channel, length, properties);

    //debug('header sent');

    var b = new Buffer(7+length+1);
    b.used = 0;
    b[b.used++] = 3; // constants.frameBody
    serializeInt(b, 2, channel);
    serializeInt(b, 4, length);

    b.utf8Write(body, b.used);
    b.used += length;

    b[b.used++] = 206; // constants.frameEnd;
    return this.write(b);

    //debug('body sent: ' + JSON.stringify(b));

  } else if (body instanceof Buffer) {
    sendHeader(this, channel, body.length, properties);

    var b = new Buffer(7);
    b.used = 0;
    b[b.used++] = 3; // constants.frameBody
    serializeInt(b, 2, channel);
    serializeInt(b, 4, body.length);
    this.write(b);

    this.write(body);

    return this.write(String.fromCharCode(206)); // frameEnd

  } else {
    // Optimize for JSON.
    // Use asciiWrite() which is much faster than utf8Write().
    var jsonBody = JSON.stringify(body);
    var length = jsonBody.length;

    debug('sending json: ' + jsonBody);

    properties = mixin({contentType: 'text/json' }, properties);

    sendHeader(this, channel, length, properties);

    var b = new Buffer(7+length+1);
    b.used = 0;

    b[b.used++] = 3; // constants.frameBody
    serializeInt(b, 2, channel);
    serializeInt(b, 4, length);

    b.asciiWrite(jsonBody, b.used);
    b.used += length;

    b[b.used++] = 206; // constants.frameEnd;
    return this.write(b);
  }
};