From 3365a4df7d6117473905ec3f633d9a1bb42b6b17 Mon Sep 17 00:00:00 2001 From: Rebecca Turner Date: Tue, 22 Jan 2019 17:01:25 -0800 Subject: [PATCH] Fix file descriptor leak on sync errors --- index.js | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/index.js b/index.js index b2405c8..7efd5d9 100644 --- a/index.js +++ b/index.js @@ -180,27 +180,30 @@ function writeFileSync (filename, data, options) { } var tmpfile = getTmpname(filename) - try { - if (!options.mode || !options.chown) { - // Either mode or chown is not explicitly set - // Default behavior is to copy it from original file - try { - var stats = fs.statSync(filename) - options = Object.assign({}, options) - if (!options.mode) { - options.mode = stats.mode - } - if (!options.chown && process.getuid) { - options.chown = { uid: stats.uid, gid: stats.gid } - } - } catch (ex) { - // ignore stat errors + if (!options.mode || !options.chown) { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + try { + var stats = fs.statSync(filename) + options = Object.assign({}, options) + if (!options.mode) { + options.mode = stats.mode } + if (!options.chown && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid } + } + } catch (ex) { + // ignore stat errors } + } + + var fd + var cleanup = cleanupOnExit(tmpfile) + var removeOnExitHandler = onExit(cleanup) + + try { - var cleanup = cleanupOnExit(tmpfile) - var removeOnExitHandler = onExit(cleanup) - var fd = fs.openSync(tmpfile, 'w', options.mode) + fd = fs.openSync(tmpfile, 'w', options.mode) if (Buffer.isBuffer(data)) { fs.writeSync(fd, data, 0, data.length, 0) } else if (data != null) { @@ -215,6 +218,7 @@ function writeFileSync (filename, data, options) { fs.renameSync(tmpfile, filename) removeOnExitHandler() } catch (err) { + if (fd) fs.closeSync(fd) removeOnExitHandler() cleanup() throw err