Skip to content

Commit 86fb658

Browse files
committed
Implemented Snapshot.export
1 parent 7a41a8b commit 86fb658

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

test/cpu_cprofiler.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,34 @@ describe('HEAP', function() {
214214
);
215215
});
216216

217+
it('should export itself to stream', function(done) {
218+
var snapshot = profiler.takeSnapshot();
219+
var fs = require('fs'),
220+
ws = fs.createWriteStream('snapshot.json');
221+
222+
snapshot.export(ws);
223+
ws.on('finish', done);
224+
});
225+
226+
it('should pipe itself to stream', function(done) {
227+
var snapshot = profiler.takeSnapshot();
228+
var fs = require('fs'),
229+
ws = fs.createWriteStream('snapshot.json')
230+
.on('finish', done);
231+
232+
snapshot.export().pipe(ws);
233+
});
234+
235+
it('should export itself to callback', function(done) {
236+
var snapshot = profiler.takeSnapshot();
237+
238+
snapshot.export(function(err, result) {
239+
expect(!err);
240+
expect(typeof result == 'string');
241+
done();
242+
});
243+
});
244+
217245
});
218246

219247
function deleteAllSnapshots() {

v8-profiler.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ var path = require('path');
33
var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json')));
44
var binding = require(binding_path);
55

6+
var Stream = require('stream').Stream,
7+
inherits = require('util').inherits;
8+
69
function Snapshot() {}
710

811
Snapshot.prototype.getHeader = function() {
@@ -35,6 +38,39 @@ Snapshot.prototype.compare = function(other) {
3538
return diff;
3639
};
3740

41+
function ExportStream() {
42+
Stream.Transform.call(this);
43+
this._transform = function noTransform(chunk, encoding, done) {
44+
done(null, chunk);
45+
}
46+
}
47+
inherits(ExportStream, Stream.Transform);
48+
49+
/**
50+
* @param {Stream.Writable|function} dataReceiver
51+
* @returns {Stream|function}
52+
*/
53+
Snapshot.prototype.export = function(dataReceiver) {
54+
dataReceiver = dataReceiver || new ExportStream();
55+
56+
var toStream = dataReceiver instanceof Stream,
57+
chunks = toStream ? null : [];
58+
59+
function onChunk(chunk, len) {
60+
if (toStream) dataReceiver.write(chunk);
61+
else chunks.push(chunk);
62+
}
63+
64+
function onDone() {
65+
if (toStream) dataReceiver.end();
66+
else dataReceiver(null, chunks.join(''));
67+
}
68+
69+
this.serialize(onChunk, onDone);
70+
71+
return dataReceiver;
72+
};
73+
3874
function nodes(snapshot) {
3975
var n = snapshot.nodesCount, i, nodes = [];
4076
for (i = 0; i < n; i++) {

0 commit comments

Comments
 (0)