Skip to content

Commit

Permalink
Implemented Snapshot.export
Browse files Browse the repository at this point in the history
  • Loading branch information
3y3 committed May 1, 2015
1 parent 10dad3b commit 69cebdc
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
28 changes: 28 additions & 0 deletions test/cpu_cprofiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,34 @@ describe('HEAP', function() {
);
});

it('should export itself to stream', function(done) {
var snapshot = profiler.takeSnapshot();
var fs = require('fs'),
ws = fs.createWriteStream('snapshot.json');

snapshot.export(ws);
ws.on('finish', done);
});

it('should pipe itself to stream', function(done) {
var snapshot = profiler.takeSnapshot();
var fs = require('fs'),
ws = fs.createWriteStream('snapshot.json')
.on('finish', done);

snapshot.export().pipe(ws);
});

it('should export itself to callback', function(done) {
var snapshot = profiler.takeSnapshot();

snapshot.export(function(err, result) {
expect(!err);
expect(typeof result == 'string');
done();
});
});

});

function deleteAllSnapshots() {
Expand Down
36 changes: 36 additions & 0 deletions v8-profiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ var path = require('path');
var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json')));
var binding = require(binding_path);

var Stream = require('stream').Stream,
inherits = require('util').inherits;

function Snapshot() {}

Snapshot.prototype.getHeader = function() {
Expand Down Expand Up @@ -35,6 +38,39 @@ Snapshot.prototype.compare = function(other) {
return diff;
};

function ExportStream() {
Stream.Transform.call(this);
this._transform = function noTransform(chunk, encoding, done) {
done(null, chunk);
}
}
inherits(ExportStream, Stream.Transform);

/**
* @param {Stream.Writable|function} dataReceiver
* @returns {Stream|function}
*/
Snapshot.prototype.export = function(dataReceiver) {
dataReceiver = dataReceiver || new ExportStream();

var toStream = dataReceiver instanceof Stream,
chunks = toStream ? null : [];

function onChunk(chunk, len) {
if (toStream) dataReceiver.write(chunk);
else chunks.push(chunk);
}

function onDone() {
if (toStream) dataReceiver.end();
else dataReceiver(null, chunks.join(''));
}

this.serialize(onChunk, onDone);

return dataReceiver;
};

function nodes(snapshot) {
var n = snapshot.nodesCount, i, nodes = [];
for (i = 0; i < n; i++) {
Expand Down

0 comments on commit 69cebdc

Please # to comment.