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