Skip to content

Instantly share code, notes, and snippets.

@davedoesdev
Last active August 12, 2016 06:08
Show Gist options
  • Save davedoesdev/a7d8f41b60733da6ac91e6a0ed25ca32 to your computer and use it in GitHub Desktop.
Save davedoesdev/a7d8f41b60733da6ac91e6a0ed25ca32 to your computer and use it in GitHub Desktop.
Using frame-stream to add a header to a stream (i.e. add only one frame to the start of the stream)

Example showing how to add a header to a stream. Uses frame-stream to add a single frame containing the header. The rest of the data is left on the stream. Can be used to add metadata to the start of a stream.

"use strict";
let frame = require('frame-stream');
function write_header(s, header)
{
var out_stream = frame.encode();
out_stream._pushFrameData = function (bufs)
{
for (let buf of bufs)
{
s.write(buf);
}
};
out_stream.end(header);
}
function read_header(s, max_size, cb)
{
if (!cb)
{
cb = max_size;
max_size = 0;
}
let in_stream = frame.decode(
{
maxSize: max_size
});
function done(v)
{
if (v)
{
throw v;
}
}
s.on('readable', function onread()
{
let data = this.read();
if (data)
{
let buffer = in_stream.buffer;
try
{
in_stream.push = done;
in_stream._transform(data, null, done);
}
catch (v)
{
s.removeListener('readable', onread);
if (v instanceof Buffer)
{
let rest = buffer ? Buffer.concat([buffer, data]) : data;
s.unshift(rest.slice(in_stream.opts.lengthSize + v.length));
return cb(null, v);
}
cb(v);
}
}
});
}
var net = require('net'),
server = net.createServer(function (socket)
{
read_header(socket, function (err, header)
{
if (err)
{
socket.on('readable', function ()
{
this.read();
});
return console.error(err);
}
console.log('header:', header.toString('utf8'));
socket.pipe(process.stdout);
});
socket.on('end', function ()
{
server.close();
});
});
server.listen(40000);
var socket = net.connect(40000, function ()
{
this.cork();
write_header(this, 'hello there');
this.end('following data');
this.uncork();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment