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'); 9const assert = require('assert'); 10 11const bench = common.createBenchmark(main, { 12 encodingType: ['buf', 'asc', 'utf'], 13 filesize: [1000 * 1024], 14 highWaterMark: [1024, 4096, 65535, 1024 * 1024], 15 n: 1024 16}); 17 18function main(conf) { 19 const { encodingType, highWaterMark, filesize } = conf; 20 let { n } = conf; 21 22 let encoding = ''; 23 switch (encodingType) { 24 case 'buf': 25 encoding = null; 26 break; 27 case 'asc': 28 encoding = 'ascii'; 29 break; 30 case 'utf': 31 encoding = 'utf8'; 32 break; 33 default: 34 throw new Error(`invalid encodingType: ${encodingType}`); 35 } 36 37 // Make file 38 const buf = Buffer.allocUnsafe(filesize); 39 if (encoding === 'utf8') { 40 // ü 41 for (let i = 0; i < buf.length; i++) { 42 buf[i] = i % 2 === 0 ? 0xC3 : 0xBC; 43 } 44 } else if (encoding === 'ascii') { 45 buf.fill('a'); 46 } else { 47 buf.fill('x'); 48 } 49 50 try { fs.unlinkSync(filename); } catch {} 51 const ws = fs.createWriteStream(filename); 52 ws.on('close', runTest.bind(null, filesize, highWaterMark, encoding, n)); 53 ws.on('drain', write); 54 write(); 55 function write() { 56 do { 57 n--; 58 } while (false !== ws.write(buf) && n > 0); 59 if (n === 0) 60 ws.end(); 61 } 62} 63 64function runTest(filesize, highWaterMark, encoding, n) { 65 assert(fs.statSync(filename).size === filesize * n); 66 const rs = fs.createReadStream(filename, { 67 highWaterMark, 68 encoding 69 }); 70 71 rs.on('open', () => { 72 bench.start(); 73 }); 74 75 let bytes = 0; 76 rs.on('data', (chunk) => { 77 bytes += chunk.length; 78 }); 79 80 rs.on('end', () => { 81 try { fs.unlinkSync(filename); } catch {} 82 // MB/sec 83 bench.end(bytes / (1024 * 1024)); 84 }); 85} 86