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