|
| 1 | +'use strict'; |
| 2 | +const common = require('../common'); |
| 3 | + |
| 4 | +// This test ensures that fs.readFile correctly returns the |
| 5 | +// contents of varying-sized files. |
| 6 | + |
| 7 | +const assert = require('assert'); |
| 8 | +const fs = require('fs'); |
| 9 | +const path = require('path'); |
| 10 | + |
| 11 | +const prefix = `.removeme-fs-readfile-${process.pid}`; |
| 12 | + |
| 13 | +common.refreshTmpDir(); |
| 14 | + |
| 15 | +const fileInfo = [ |
| 16 | + { name: path.join(common.tmpDir, `${prefix}-1K.txt`), |
| 17 | + len: 1024, |
| 18 | + }, |
| 19 | + { name: path.join(common.tmpDir, `${prefix}-64K.txt`), |
| 20 | + len: 64 * 1024, |
| 21 | + }, |
| 22 | + { name: path.join(common.tmpDir, `${prefix}-64KLessOne.txt`), |
| 23 | + len: (64 * 1024) - 1, |
| 24 | + }, |
| 25 | + { name: path.join(common.tmpDir, `${prefix}-1M.txt`), |
| 26 | + len: 1 * 1024 * 1024, |
| 27 | + }, |
| 28 | + { name: path.join(common.tmpDir, `${prefix}-1MPlusOne.txt`), |
| 29 | + len: (1 * 1024 * 1024) + 1, |
| 30 | + }, |
| 31 | +]; |
| 32 | + |
| 33 | +// Populate each fileInfo (and file) with unique fill. |
| 34 | +const sectorSize = 512; |
| 35 | +for (const e of fileInfo) { |
| 36 | + e.contents = Buffer.allocUnsafe(e.len); |
| 37 | + |
| 38 | + // This accounts for anything unusual in Node's implementation of readFile. |
| 39 | + // Using e.g. 'aa...aa' would miss bugs like Node re-reading |
| 40 | + // the same section twice instead of two separate sections. |
| 41 | + for (let offset = 0; offset < e.len; offset += sectorSize) { |
| 42 | + const fillByte = 256 * Math.random(); |
| 43 | + const nBytesToFill = Math.min(sectorSize, e.len - offset); |
| 44 | + e.contents.fill(fillByte, offset, offset + nBytesToFill); |
| 45 | + } |
| 46 | + |
| 47 | + fs.writeFileSync(e.name, e.contents); |
| 48 | +} |
| 49 | +// All files are now populated. |
| 50 | + |
| 51 | +// Test readFile on each size. |
| 52 | +for (const e of fileInfo) { |
| 53 | + fs.readFile(e.name, common.mustCall((err, buf) => { |
| 54 | + console.log(`Validating readFile on file ${e.name} of length ${e.len}`); |
| 55 | + assert.ifError(err, 'An error occurred'); |
| 56 | + assert.deepStrictEqual(buf, e.contents, 'Incorrect file contents'); |
| 57 | + })); |
| 58 | +} |
0 commit comments