From 408bfece510520d73d9e19629450dfec691cc1e6 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Tue, 12 Jun 2012 15:32:40 +0200 Subject: [PATCH] fs: fix infinite loop in fs.readFile() Fix an infinite loop in the case where the file got truncated by a concurrent writer while fs.readFile() was busy reading in the file. --- lib/fs.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index cedb9b1614..f2fcb69a0e 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -148,18 +148,18 @@ fs.readFile = function(path, encoding_) { }); } + if (bytesRead === 0) { + return close(); + } + pos += bytesRead; if (size !== 0) { if (pos === size) close(); else read(); } else { // unknown size, just read until we don't get bytes. - if (bytesRead > 0) { - buffers.push(buffer.slice(0, bytesRead)); - read(); - } else { - close(); - } + buffers.push(buffer.slice(0, bytesRead)); + read(); } } @@ -168,6 +168,8 @@ fs.readFile = function(path, encoding_) { if (size === 0) { // collected the data into the buffers list. buffer = Buffer.concat(buffers, pos); + } else if (pos < size) { + buffer = buffer.slice(0, pos); } if (encoding) buffer = buffer.toString(encoding);