diff --git a/lib/fs.js b/lib/fs.js index 77bcbac61a5eca..472d03cc75414c 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -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); } } @@ -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);