如何在Node.js中测试流?
我试过了benchmark.js:
var fs = require('fs');
var Transform = require('readable-stream').Transform;
var util = require('util');
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
// my super uppercase stream
function Uppercase(options) {
if (!(this instanceof Uppercase))
return new Uppercase(options);
Transform.call(this, options);
}
Uppercase.prototype = Object.create(
Transform.prototype, { constructor: { value: Uppercase }});
Uppercase.prototype._transform = function(chunk, encoding, done) {
chunk = chunk.toString().toUpperCase();
this.push(chunk)
};
// start benchmarking
suite.add('stream test', function() {
var reader = fs.createReadStream('in.txt');
var parser = new Uppercase();
var writer = fs.createWriteStream('out.txt');
reader.pipe(parser).pipe(writer);
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
// run async
.run();
suite.run();
但是我得到了错误
Unhandled stream error in pipe
您的代码遇到这个错误,您可以通过监听阅读器和写入器上的错误来查看:
[Error: EMFILE, open 'out.txt'] errno: 20, code: 'EMFILE', path: 'in.txt'
[Error: EMFILE, open 'out.txt'] errno: 20, code: 'EMFILE', path: 'out.txt'
这是由于流是异步的,并且在结束时没有显式的回调。所以你在in.txt和out.txt之间创建了成千上万个管道流,直到系统告诉你打开的文件描述符太多了。
所以,我猜通过"对Node中的流进行基准测试",你想要计算的是同步执行此操作所需的时间:
reader.pipe(filter).pipe(writer)
在这种情况下,你需要:
- 使用benchmark的defer选项
- 当管道操作在node.js文档
这个答案的代码已经用节点0.10.0进行了测试,但我想唯一的区别应该是在持有Transform
的模块的名称:
var fs = require('fs');
var util = require('util');
var Transform = require('stream').Transform;
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
var i = 0;
// my super uppercase stream
function Uppercase(options) {
if (!(this instanceof Uppercase))
return new Uppercase(options);
Transform.call(this, options);
}
Uppercase.prototype = Object.create(
Transform.prototype, { constructor: { value: Uppercase }}
);
Uppercase.prototype._transform = function(chunk, encoding, done) {
chunk = chunk.toString().toUpperCase();
this.push(chunk)
};
// start benchmarking
suite.add('stream test', {
'defer' : true,
'fn' : function (deferred) {
var reader = fs.createReadStream('in.txt');
var parser = new Uppercase();
var writer = fs.createWriteStream('out.txt');
reader.on('error', function (err) {
console.log(err);
});
writer.on('error', function (err) {
console.log(err);
});
reader.on('end', function (argument) {
// Wait until reader is over and then close reader and finish deferred test
writer.end();
deferred.resolve();
});
reader.pipe(parser).pipe(writer, {'end': false});
}
})
// listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
// run async
.run();