@@ -180,27 +180,30 @@ function writeFileSync (filename, data, options) {
180180 }
181181 var tmpfile = getTmpname ( filename )
182182
183- try {
184- if ( ! options . mode || ! options . chown ) {
185- // Either mode or chown is not explicitly set
186- // Default behavior is to copy it from original file
187- try {
188- var stats = fs . statSync ( filename )
189- options = Object . assign ( { } , options )
190- if ( ! options . mode ) {
191- options . mode = stats . mode
192- }
193- if ( ! options . chown && process . getuid ) {
194- options . chown = { uid : stats . uid , gid : stats . gid }
195- }
196- } catch ( ex ) {
197- // ignore stat errors
183+ if ( ! options . mode || ! options . chown ) {
184+ // Either mode or chown is not explicitly set
185+ // Default behavior is to copy it from original file
186+ try {
187+ var stats = fs . statSync ( filename )
188+ options = Object . assign ( { } , options )
189+ if ( ! options . mode ) {
190+ options . mode = stats . mode
198191 }
192+ if ( ! options . chown && process . getuid ) {
193+ options . chown = { uid : stats . uid , gid : stats . gid }
194+ }
195+ } catch ( ex ) {
196+ // ignore stat errors
199197 }
198+ }
199+
200+ var fd
201+ var cleanup = cleanupOnExit ( tmpfile )
202+ var removeOnExitHandler = onExit ( cleanup )
203+
204+ try {
200205
201- var cleanup = cleanupOnExit ( tmpfile )
202- var removeOnExitHandler = onExit ( cleanup )
203- var fd = fs . openSync ( tmpfile , 'w' , options . mode )
206+ fd = fs . openSync ( tmpfile , 'w' , options . mode )
204207 if ( Buffer . isBuffer ( data ) ) {
205208 fs . writeSync ( fd , data , 0 , data . length , 0 )
206209 } else if ( data != null ) {
@@ -215,6 +218,7 @@ function writeFileSync (filename, data, options) {
215218 fs . renameSync ( tmpfile , filename )
216219 removeOnExitHandler ( )
217220 } catch ( err ) {
221+ if ( fd ) fs . closeSync ( fd )
218222 removeOnExitHandler ( )
219223 cleanup ( )
220224 throw err
0 commit comments