diff --git a/test/cpu_cprofiler.js b/test/cpu_cprofiler.js index dd42c58..122fe7d 100644 --- a/test/cpu_cprofiler.js +++ b/test/cpu_cprofiler.js @@ -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() { diff --git a/v8-profiler.js b/v8-profiler.js index 63e6552..155f460 100644 --- a/v8-profiler.js +++ b/v8-profiler.js @@ -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() { @@ -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++) {