Skip to content

Commit c9207f7

Browse files
olovpiscisaureus
authored andcommitted
fs: fix corruption in writeFile and writeFileSync
1. writeFileSync bumps position incorrectly, causing it to drift in iteration three and onwards. 2. Append mode files will get corrupted in the middle if writeFile or writeFileSync iterates multiple times, unless running on Linux. position starts out as null so first write is OK, but then position will refer to a location inside an existing file, corrupting that data. Linux ignores position for append mode files so it doesn't happen there. This commit fixes these two related issues by bumping position correctly and by always using null as the position argument to write/writeSync for append mode files. PR-URL: #1063 Reviewed-By: Bert Belder <[email protected]>
1 parent 4e9bf93 commit c9207f7

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

lib/fs.js

+11-5
Original file line numberDiff line numberDiff line change
@@ -1099,7 +1099,9 @@ function writeAll(fd, buffer, offset, length, position, callback) {
10991099
} else {
11001100
offset += written;
11011101
length -= written;
1102-
position += written;
1102+
if (position !== null) {
1103+
position += written;
1104+
}
11031105
writeAll(fd, buffer, offset, length, position, callback);
11041106
}
11051107
}
@@ -1148,13 +1150,17 @@ fs.writeFileSync = function(path, data, options) {
11481150
if (!(data instanceof Buffer)) {
11491151
data = new Buffer('' + data, options.encoding || 'utf8');
11501152
}
1151-
var written = 0;
1153+
var offset = 0;
11521154
var length = data.length;
11531155
var position = /a/.test(flag) ? null : 0;
11541156
try {
1155-
while (written < length) {
1156-
written += fs.writeSync(fd, data, written, length - written, position);
1157-
position += written;
1157+
while (length > 0) {
1158+
var written = fs.writeSync(fd, data, offset, length, position);
1159+
offset += written;
1160+
length -= written;
1161+
if (position !== null) {
1162+
position += written;
1163+
}
11581164
}
11591165
} finally {
11601166
fs.closeSync(fd);

0 commit comments

Comments
 (0)