From 9fc598b7c28e80a18e1eff106c2f6bfd0d4f3e20 Mon Sep 17 00:00:00 2001 From: Olov Lassus Date: Thu, 5 Mar 2015 01:03:34 +0100 Subject: [PATCH] fs: fix partial write 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. --- lib/fs.js | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index b2aba37f561be8..0b534c14fe0f47 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1097,7 +1097,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); } } @@ -1146,13 +1148,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);