1// Call fs.promises.writeFile over and over again really fast.
2// Then see how many times it got called.
3// Yes, this is a silly benchmark.  Most benchmarks are silly.
4'use strict';
5
6const path = require('path');
7const common = require('../common.js');
8const fs = require('fs');
9const assert = require('assert');
10const tmpdir = require('../../test/common/tmpdir');
11
12tmpdir.refresh();
13const filename = path.resolve(tmpdir.path,
14                              `.removeme-benchmark-garbage-${process.pid}`);
15let filesWritten = 0;
16const bench = common.createBenchmark(main, {
17  duration: [5],
18  encodingType: ['buf', 'asc', 'utf'],
19  size: [2, 1024, 65535, 1024 * 1024],
20  concurrent: [1, 10],
21});
22
23function main({ encodingType, duration, concurrent, size }) {
24  let encoding;
25  let chunk;
26  switch (encodingType) {
27    case 'buf':
28      chunk = Buffer.alloc(size, 'b');
29      break;
30    case 'asc':
31      chunk = 'a'.repeat(size);
32      encoding = 'ascii';
33      break;
34    case 'utf':
35      chunk = 'ü'.repeat(Math.ceil(size / 2));
36      encoding = 'utf8';
37      break;
38    default:
39      throw new Error(`invalid encodingType: ${encodingType}`);
40  }
41
42  let writes = 0;
43  let benchEnded = false;
44  bench.start();
45  setTimeout(() => {
46    benchEnded = true;
47    bench.end(writes);
48    for (let i = 0; i < filesWritten; i++) {
49      try {
50        fs.unlinkSync(`${filename}-${i}`);
51      } catch {
52        // Continue regardless of error.
53      }
54    }
55    process.exit(0);
56  }, duration * 1000);
57
58  function write() {
59    fs.promises.writeFile(`${filename}-${filesWritten++}`, chunk, encoding)
60      .then(() => afterWrite())
61      .catch((err) => afterWrite(err));
62  }
63
64  function afterWrite(er) {
65    if (er) {
66      if (er.code === 'ENOENT') {
67        // Only OK if unlinked by the timer from main.
68        assert.ok(benchEnded);
69        return;
70      }
71      throw er;
72    }
73
74    writes++;
75    if (!benchEnded)
76      write();
77  }
78
79  while (concurrent--) write();
80}
81