Skip to content

Commit

Permalink
fs: fix corruption in writeFile and writeFileSync
Browse files Browse the repository at this point in the history
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: nodejs#1063
Reviewed-By: Bert Belder <bertbelder@gmail.com>
  • Loading branch information
olov authored and piscisaureus committed Mar 25, 2015
1 parent 4e9bf93 commit c9207f7
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -1099,7 +1099,9 @@ function writeAll(fd, buffer, offset, length, position, callback) {
} else {
offset += written;
length -= written;
position += written;
if (position !== null) {
position += written;
}
writeAll(fd, buffer, offset, length, position, callback);
}
}
Expand Down Expand Up @@ -1148,13 +1150,17 @@ fs.writeFileSync = function(path, data, options) {
if (!(data instanceof Buffer)) {
data = new Buffer('' + data, options.encoding || 'utf8');
}
var written = 0;
var offset = 0;
var length = data.length;
var position = /a/.test(flag) ? null : 0;
try {
while (written < length) {
written += fs.writeSync(fd, data, written, length - written, position);
position += written;
while (length > 0) {
var written = fs.writeSync(fd, data, offset, length, position);
offset += written;
length -= written;
if (position !== null) {
position += written;
}
}
} finally {
fs.closeSync(fd);
Expand Down

0 comments on commit c9207f7

Please sign in to comment.