• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 { fs.unlinkSync(`${filename}-${i}`); } catch { }
50    }
51    process.exit(0);
52  }, duration * 1000);
53
54  function write() {
55    fs.promises.writeFile(`${filename}-${filesWritten++}`, chunk, encoding)
56      .then(() => afterWrite())
57      .catch((err) => afterWrite(err));
58  }
59
60  function afterWrite(er) {
61    if (er) {
62      if (er.code === 'ENOENT') {
63        // Only OK if unlinked by the timer from main.
64        assert.ok(benchEnded);
65        return;
66      }
67      throw er;
68    }
69
70    writes++;
71    if (!benchEnded)
72      write();
73  }
74
75  while (concurrent--) write();
76}
77