node/test/parallel/test-fs-writefile-with-fd.js
Sakthipriyan Vairamani (thefourtheye) 8f4b924f4a fs: make writeFile consistent with readFile wrt fd
As it is, `readFile` always reads from the current position of the file,
if a file descriptor is used. But `writeFile` always writes from the
beginning of the file.

This patch fixes this inconsistency by making `writeFile` also to write
from the current position of the file when used with a file descriptor.

PR-URL: https://github.com/nodejs/node/pull/23709
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Vse Mozhet Byt <vsemozhetbyt@gmail.com>
Reviewed-By: Sam Roberts <vieuxtech@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com>
Reviewed-By: Rod Vagg <rod@vagg.org>
Reviewed-By: Anatoli Papirovski <apapirovski@mac.com>
Reviewed-By: Сковорода Никита Андреевич <chalkerx@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
2018-12-15 12:54:50 -08:00

59 lines
1.7 KiB
JavaScript

'use strict';
/*
* This test makes sure that `writeFile()` always writes from the current
* position of the file, instead of truncating the file, when used with file
* descriptors.
*/
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const join = require('path').join;
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
{
/* writeFileSync() test. */
const filename = join(tmpdir.path, 'test.txt');
/* Open the file descriptor. */
const fd = fs.openSync(filename, 'w');
/* Write only five characters, so that the position moves to five. */
assert.deepStrictEqual(fs.writeSync(fd, 'Hello'), 5);
assert.deepStrictEqual(fs.readFileSync(filename).toString(), 'Hello');
/* Write some more with writeFileSync(). */
fs.writeFileSync(fd, 'World');
/* New content should be written at position five, instead of zero. */
assert.deepStrictEqual(fs.readFileSync(filename).toString(), 'HelloWorld');
}
{
/* writeFile() test. */
const file = join(tmpdir.path, 'test1.txt');
/* Open the file descriptor. */
fs.open(file, 'w', common.mustCall((err, fd) => {
assert.ifError(err);
/* Write only five characters, so that the position moves to five. */
fs.write(fd, 'Hello', common.mustCall((err, bytes) => {
assert.ifError(err);
assert.strictEqual(bytes, 5);
assert.deepStrictEqual(fs.readFileSync(file).toString(), 'Hello');
/* Write some more with writeFile(). */
fs.writeFile(fd, 'World', common.mustCall((err) => {
assert.ifError(err);
/* New content should be written at position five, instead of zero. */
assert.deepStrictEqual(fs.readFileSync(file).toString(), 'HelloWorld');
}));
}));
}));
}