|
| 1 | +// test the througput of the fs.WriteStream class. |
| 2 | + |
| 3 | +var path = require('path'); |
| 4 | +var common = require('../common.js'); |
| 5 | +var filename = path.resolve(__dirname, '.removeme-benchmark-garbage'); |
| 6 | +var fs = require('fs'); |
| 7 | + |
| 8 | +var bench = common.createBenchmark(main, { |
| 9 | + dur: [1, 3], |
| 10 | + type: ['buf', 'asc', 'utf'], |
| 11 | + size: [2, 1024, 65535, 1024 * 1024] |
| 12 | +}); |
| 13 | + |
| 14 | +function main(conf) { |
| 15 | + var dur = +conf.dur; |
| 16 | + var type = conf.type; |
| 17 | + var size = +conf.size; |
| 18 | + var encoding; |
| 19 | + |
| 20 | + var chunk; |
| 21 | + switch (type) { |
| 22 | + case 'buf': |
| 23 | + chunk = new Buffer(size); |
| 24 | + chunk.fill('b'); |
| 25 | + break; |
| 26 | + case 'asc': |
| 27 | + chunk = new Array(size + 1).join('a'); |
| 28 | + encoding = 'ascii'; |
| 29 | + break; |
| 30 | + case 'utf': |
| 31 | + chunk = new Array(Math.ceil(size/2) + 1).join('ü'); |
| 32 | + encoding = 'utf8'; |
| 33 | + break; |
| 34 | + default: |
| 35 | + throw new Error('invalid type'); |
| 36 | + } |
| 37 | + |
| 38 | + try { fs.unlinkSync(filename); } catch (e) {} |
| 39 | + |
| 40 | + var started = false; |
| 41 | + var ending = false; |
| 42 | + var ended = false; |
| 43 | + setTimeout(function() { |
| 44 | + ending = true; |
| 45 | + f.end(); |
| 46 | + }, dur * 1000); |
| 47 | + |
| 48 | + var f = fs.createWriteStream(filename); |
| 49 | + f.on('drain', write); |
| 50 | + f.on('open', write); |
| 51 | + f.on('close', done); |
| 52 | + f.on('finish', function() { |
| 53 | + ended = true; |
| 54 | + var written = fs.statSync(filename).size / 1024; |
| 55 | + try { fs.unlinkSync(filename); } catch (e) {} |
| 56 | + bench.end(written / 1024); |
| 57 | + }); |
| 58 | + |
| 59 | + |
| 60 | + function write() { |
| 61 | + // don't try to write after we end, even if a 'drain' event comes. |
| 62 | + // v0.8 streams are so sloppy! |
| 63 | + if (ending) |
| 64 | + return; |
| 65 | + |
| 66 | + if (!started) { |
| 67 | + started = true; |
| 68 | + bench.start(); |
| 69 | + } |
| 70 | + |
| 71 | + while (false !== f.write(chunk, encoding)); |
| 72 | + } |
| 73 | + |
| 74 | + function done() { |
| 75 | + if (!ended) |
| 76 | + f.emit('finish'); |
| 77 | + } |
| 78 | +} |
0 commit comments