|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Test of fs.readFile with different flags. |
| 4 | +const common = require('../common'); |
| 5 | +const fs = require('fs'); |
| 6 | +const assert = require('assert'); |
| 7 | +const path = require('path'); |
| 8 | +const tmpdir = require('../common/tmpdir'); |
| 9 | + |
| 10 | +tmpdir.refresh(); |
| 11 | + |
| 12 | +{ |
| 13 | + const emptyFile = path.join(tmpdir.path, 'empty.txt'); |
| 14 | + fs.closeSync(fs.openSync(emptyFile, 'w')); |
| 15 | + |
| 16 | + fs.readFile( |
| 17 | + emptyFile, |
| 18 | + // With `a+` the file is created if it does not exist |
| 19 | + { encoding: 'utf8', flag: 'a+' }, |
| 20 | + common.mustCall((err, data) => { assert.strictEqual(data, ''); }) |
| 21 | + ); |
| 22 | + |
| 23 | + fs.readFile( |
| 24 | + emptyFile, |
| 25 | + // Like `a+` but fails if the path exists. |
| 26 | + { encoding: 'utf8', flag: 'ax+' }, |
| 27 | + common.mustCall((err, data) => { assert.strictEqual(err.code, 'EEXIST'); }) |
| 28 | + ); |
| 29 | +} |
| 30 | + |
| 31 | +{ |
| 32 | + const willBeCreated = path.join(tmpdir.path, 'will-be-created'); |
| 33 | + |
| 34 | + fs.readFile( |
| 35 | + willBeCreated, |
| 36 | + // With `a+` the file is created if it does not exist |
| 37 | + { encoding: 'utf8', flag: 'a+' }, |
| 38 | + common.mustCall((err, data) => { assert.strictEqual(data, ''); }) |
| 39 | + ); |
| 40 | +} |
| 41 | + |
| 42 | +{ |
| 43 | + const willNotBeCreated = path.join(tmpdir.path, 'will-not-be-created'); |
| 44 | + |
| 45 | + fs.readFile( |
| 46 | + willNotBeCreated, |
| 47 | + // Default flag is `r`. An exception occurs if the file does not exist. |
| 48 | + { encoding: 'utf8' }, |
| 49 | + common.mustCall((err, data) => { assert.strictEqual(err.code, 'ENOENT'); }) |
| 50 | + ); |
| 51 | +} |
0 commit comments