1'use strict'; 2 3/* 4 * This test makes sure that `writeFile()` always writes from the current 5 * position of the file, instead of truncating the file, when used with file 6 * descriptors. 7 */ 8 9const common = require('../common'); 10const assert = require('assert'); 11const fs = require('fs'); 12const join = require('path').join; 13 14const tmpdir = require('../common/tmpdir'); 15tmpdir.refresh(); 16 17{ 18 /* writeFileSync() test. */ 19 const filename = join(tmpdir.path, 'test.txt'); 20 21 /* Open the file descriptor. */ 22 const fd = fs.openSync(filename, 'w'); 23 24 /* Write only five characters, so that the position moves to five. */ 25 assert.deepStrictEqual(fs.writeSync(fd, 'Hello'), 5); 26 assert.deepStrictEqual(fs.readFileSync(filename).toString(), 'Hello'); 27 28 /* Write some more with writeFileSync(). */ 29 fs.writeFileSync(fd, 'World'); 30 31 /* New content should be written at position five, instead of zero. */ 32 assert.deepStrictEqual(fs.readFileSync(filename).toString(), 'HelloWorld'); 33} 34 35{ 36 /* writeFile() test. */ 37 const file = join(tmpdir.path, 'test1.txt'); 38 39 /* Open the file descriptor. */ 40 fs.open(file, 'w', common.mustCall((err, fd) => { 41 assert.ifError(err); 42 43 /* Write only five characters, so that the position moves to five. */ 44 fs.write(fd, 'Hello', common.mustCall((err, bytes) => { 45 assert.ifError(err); 46 assert.strictEqual(bytes, 5); 47 assert.deepStrictEqual(fs.readFileSync(file).toString(), 'Hello'); 48 49 /* Write some more with writeFile(). */ 50 fs.writeFile(fd, 'World', common.mustCall((err) => { 51 assert.ifError(err); 52 53 /* New content should be written at position five, instead of zero. */ 54 assert.deepStrictEqual(fs.readFileSync(file).toString(), 'HelloWorld'); 55 })); 56 })); 57 })); 58} 59