From 0385b17ce06b7c12ad3e4035477f6a0cf897580e Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Tue, 12 Jun 2012 16:04:56 +0200 Subject: [PATCH] fs: fix infinite loop in fs.readFileSync() Fix an infinite loop in the case where the file got truncated by a concurrent writer while fs.readFileSync() was busy reading in the file. --- lib/fs.js | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index f2fcb69..4e3574e 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -221,12 +221,7 @@ fs.readFileSync = function(path, encoding) { } pos += bytesRead; - - if (size !== 0) { - done = pos >= size; - } else { - done = bytesRead >= 0; - } + done = (bytesRead === 0) || (size !== 0 && pos >= size); } fs.closeSync(fd); @@ -234,6 +229,8 @@ fs.readFileSync = function(path, encoding) { if (size === 0) { // data was collected into the buffers list. buffer = Buffer.concat(buffers, pos); + } else if (pos < size) { + buffer = buffer.slice(0, pos); } if (encoding) buffer = buffer.toString(encoding); -- 2.7.4