Skip to content

Instantly share code, notes, and snippets.

@joelverhagen
Created August 10, 2012 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelverhagen/3315347 to your computer and use it in GitHub Desktop.
Save joelverhagen/3315347 to your computer and use it in GitHub Desktop.
Requires DelimEmitter from my Loggie project.
"use strict";
var DelimEmitter = require("./delimemitter").DelimEmitter;
exports.countInString = function(haystack, needle) {
var count = 0;
var position = 0;
while(true) {
position = haystack.indexOf(needle, position);
if(position !== -1) {
count += 1;
position += needle.length;
} else{
break;
}
}
return count;
};
exports.countInStream = function(stream, needle, callback) {
// Argument validation
if(typeof stream !== "object") {
throw new Error("The stream must be a Read Stream.");
}
if(typeof needle !== "string" && !Buffer.isBuffer(needle)) {
throw new Error("The needle must be a string or a Buffer.");
}
if(typeof callback !== "function") {
throw new Error("The callback must be a function.");
}
// turn the needle to a Buffer if need be
if(typeof needle === "string") {
needle = new Buffer(needle);
}
var callbackFired = false;
var count = 0;
var lastData;
var delimemitter = new DelimEmitter(stream, {
delimiter: needle,
includeDelimiter: true
});
// each data block should contain a delimiter, except perhaps the last
delimemitter.on("data", function(data) {
lastData = data;
count += 1;
});
// if there is an error on the stream
stream.on("error", function(error) {
if(!callbackFired) {
callback(error);
callbackFired = true;
}
});
// when we've hit the end of the file, return the number of occurrences
stream.on("end", function() {
if(!callbackFired) {
// if the last data block doesn't actually contain a delimiter, then subtract it
if(lastData.indexOf(needle) === -1) {
count -= 1;
}
callback(null, count);
callbackFired = true;
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment