Browse files

Add possibility to use different break characters.

carry gains a fourth optional argument, which can be a string
or a regular expression, based on which the stream is broken up.

Also add a test for that functionality.
  • Loading branch information...
1 parent 7fb5ab4 commit 1415f6a31cd14f0678e6869e213a338687d89369 @pgeorgi pgeorgi committed Mar 18, 2012
Showing with 50 additions and 6 deletions.
  1. +8 −6 lib/carrier.js
  2. +42 −0 test/test_other_breaks.js
View
14 lib/carrier.js
@@ -1,11 +1,15 @@
var util = require('util'),
events = require('events');
-function Carrier(reader, listener, encoding) {
+function Carrier(reader, listener, encoding, separator) {
var self = this;
self.reader = reader;
+ if (!separator) {
+ separator = /\r?\n/;
+ }
+
if (listener) {
self.addListener('line', listener);
}
@@ -14,18 +18,16 @@ function Carrier(reader, listener, encoding) {
reader.setEncoding(encoding || 'utf-8');
reader.on('data', function(data) {
- var lines = (buffer + data).split("\n");
+ var lines = (buffer + data).split(separator);
buffer = lines.pop();
lines.forEach(function(line, index) {
- line = line.replace("\r", '');
self.emit('line', line);
});
});
var ender = function() {
if (buffer.length > 0) {
- buffer = buffer.replace("\r", '');
self.emit('line', buffer);
buffer = '';
}
@@ -37,7 +39,7 @@ function Carrier(reader, listener, encoding) {
util.inherits(Carrier, events.EventEmitter);
-exports.carry = function(reader, listener, encoding) {
- return new Carrier(reader, listener, encoding);
+exports.carry = function(reader, listener, encoding, separator) {
+ return new Carrier(reader, listener, encoding, separator);
}
View
42 test/test_other_breaks.js
@@ -0,0 +1,42 @@
+var net = require('net'),
+ tap = require('tap'),
+ carrier = require('../lib/carrier.js');
+
+tap.test("non-default breaks", function(t) {
+ var server;
+ var port = 4001;
+ var to_be_sents = ["Hel", "lo\n", "Wor", "ld\n", "Glorious", " place"];
+ var expecteds = to_be_sents.join('').split("l");
+
+ t.plan(expecteds.length);
+
+ server = net.createServer(function(conn) {
+ var received_lines = -1;
+ carrier.carry(conn, function(line) {
+ received_lines ++;
+ t.equal(line, expecteds[received_lines]);
+ }, "ascii", "l");
+ });
+ server.listen(port);
+
+ var client = net.createConnection(port);
+ client.on('connect', function() {
+ var sent_lines = 0;
+ var next = function() {
+ if (sent_lines !== to_be_sents.length) {
+ client.write(to_be_sents[sent_lines], function() {
+ sent_lines ++;
+ next();
+ });
+ }
+ else {
+ client.end();
+ }
+ };
+ next();
+ });
+
+ t.on("end", function() {
+ server.close();
+ });
+});

0 comments on commit 1415f6a

Please sign in to comment.