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 { fs.unlinkSync(filename); } catch {} 40 41 let started = false; 42 let ended = false; 43 44 const f = fs.createWriteStream(filename); 45 f.on('drain', write); 46 f.on('open', write); 47 f.on('close', done); 48 f.on('finish', () => { 49 ended = true; 50 const written = fs.statSync(filename).size / 1024; 51 try { fs.unlinkSync(filename); } catch {} 52 bench.end(written / 1024); 53 }); 54 55 56 function write() { 57 if (!started) { 58 started = true; 59 setTimeout(() => { 60 f.end(); 61 }, dur * 1000); 62 bench.start(); 63 } 64 65 while (false !== f.write(chunk, encoding)); 66 } 67 68 function done() { 69 if (!ended) 70 f.emit('finish'); 71 } 72} 73