Skip to content

Commit

Permalink
Merge pull request #33 from popomore/clone-stream
Browse files Browse the repository at this point in the history
Clone stream
  • Loading branch information
yocontra committed Aug 29, 2014
2 parents 76165e0 + d37b57b commit 3dedd52
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
19 changes: 14 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ var isBuffer = require('./lib/isBuffer');
var isStream = require('./lib/isStream');
var isNull = require('./lib/isNull');
var inspectStream = require('./lib/inspectStream');
var Stream = require('stream');

function File(file) {
if (!file) file = {};
Expand Down Expand Up @@ -72,7 +73,15 @@ File.prototype.clone = function(opt) {
}
}, this);

file.contents = opt.contents && this.isBuffer() ? cloneBuffer(this.contents) : this.contents;
if (this.isStream()) {
file.contents = this.contents.pipe(new Stream.PassThrough());
this.contents = this.contents.pipe(new Stream.PassThrough());
} else if (opt.contents && this.isBuffer()) {
file.contents = cloneBuffer(this.contents);
} else {
file.contents = this.contents;
}

file.stat = this.stat ? cloneStats(this.stat) : null;

return file;
Expand All @@ -93,10 +102,10 @@ File.prototype.pipe = function(stream, opt) {
}
return stream;
}
if (this.isNull()) {
if (opt.end) stream.end();
return stream;
}

// isNull
if (opt.end) stream.end();
return stream;
};

File.prototype.inspect = function() {
Expand Down
19 changes: 17 additions & 2 deletions test/File.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
var Stream = require('stream');
var fs = require('fs');
var path = require('path');
var es = require('event-stream');

var should = require('should');
require('mocha');
Expand Down Expand Up @@ -238,20 +239,34 @@ function testFile(File) {
});

it('should copy all attributes over with Stream', function(done) {
var contents = new Stream.PassThrough();
var options = {
cwd: '/',
base: '/test/',
path: '/test/test.coffee',
contents: new Stream()
contents: contents
};
var file = new File(options);
var file2 = file.clone();

contents.write(new Buffer('wa'));

process.nextTick(function() {
contents.write(new Buffer('dup'));
contents.end();
});

file2.should.not.equal(file, 'refs should be different');
file2.cwd.should.equal(file.cwd);
file2.base.should.equal(file.base);
file2.path.should.equal(file.path);
file2.contents.should.equal(file.contents, 'stream ref should be the same');
file2.contents.should.not.equal(file.contents, 'stream ref should not be the same');
file.contents.pipe(es.wait(function(err, data) {
file2.contents.pipe(es.wait(function(err, data2) {
data2.should.not.equal(data, 'stream contents ref should not be the same');
data2.should.eql(data, 'stream contents should be the same');
}));
}));
done();
});

Expand Down

0 comments on commit 3dedd52

Please sign in to comment.