Last active
August 29, 2015 14:14
-
-
Save isabek/5b5c5863218b9dfd5864 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var through = require("through"); | |
var split = require("split"); | |
var fs = require("fs"); | |
var util = require("util"); | |
var combine = require("stream-combiner"); | |
var Readable = require("stream").Readable; | |
function MyReadable(dir) { | |
this._queue = [dir]; | |
Readable.call(this); | |
} | |
util.inherits(MyReadable, Readable); | |
MyReadable.prototype._read = function () { | |
var self = this; | |
var queue = this._queue; | |
if (!queue.length) { | |
push(null); | |
return; | |
} | |
function push(data) { | |
self.push(data); | |
} | |
var dir = queue.shift(); | |
fs.readdir(dir, function (err, list) { | |
if (err) self.emit("error", err); | |
push(list.toString().split(",").join("\n")); | |
}); | |
}; | |
function head(amount) { | |
amount = Math.abs(amount); | |
var counter = 0; | |
return combine(split("\n"), through(function (line) { | |
if (++counter > amount) this.queue(null); | |
if (counter > 1) | |
this.queue("\n"); | |
this.queue(line); | |
})); | |
} | |
function tail(lines) { | |
lines = Math.abs(lines); | |
var buffer = []; | |
return combine(split("\n"), through(function (line) { | |
buffer.push(line); | |
}, function () { | |
buffer = buffer.slice(-lines); | |
while (buffer.length) { | |
this.queue(buffer.shift()); | |
this.queue("\n"); | |
} | |
this.queue(null); | |
})); | |
} | |
new MyReadable(__dirname) | |
.pipe(head(5)) | |
.pipe(tail(3)) | |
.pipe(process.stdout); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment