forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwrite-stream-throughput.js
80 lines (68 loc) · 1.66 KB
/
write-stream-throughput.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Test the throughput of the fs.WriteStream class.
'use strict';
const path = require('path');
const common = require('../common.js');
const fs = require('fs');
const tmpdir = require('../../test/common/tmpdir');
tmpdir.refresh();
const filename = path.resolve(tmpdir.path,
`.removeme-benchmark-garbage-${process.pid}`);
const bench = common.createBenchmark(main, {
dur: [5],
encodingType: ['buf', 'asc', 'utf'],
size: [2, 1024, 65535, 1024 * 1024],
});
function main({ dur, encodingType, size }) {
let encoding;
let chunk;
switch (encodingType) {
case 'buf':
chunk = Buffer.alloc(size, 'b');
break;
case 'asc':
chunk = 'a'.repeat(size);
encoding = 'ascii';
break;
case 'utf':
chunk = 'ü'.repeat(Math.ceil(size / 2));
encoding = 'utf8';
break;
default:
throw new Error(`invalid encodingType: ${encodingType}`);
}
try {
fs.unlinkSync(filename);
} catch {
// Continue regardless of error.
}
let started = false;
let ended = false;
const f = fs.createWriteStream(filename);
f.on('drain', write);
f.on('open', write);
f.on('close', done);
f.on('finish', () => {
ended = true;
const written = fs.statSync(filename).size / 1024;
try {
fs.unlinkSync(filename);
} catch {
// Continue regardless of error.
}
bench.end(written / 1024);
});
function write() {
if (!started) {
started = true;
setTimeout(() => {
f.end();
}, dur * 1000);
bench.start();
}
while (false !== f.write(chunk, encoding));
}
function done() {
if (!ended)
f.emit('finish');
}
}