@@ -180,27 +180,30 @@ function writeFileSync (filename, data, options) {
180
180
}
181
181
var tmpfile = getTmpname ( filename )
182
182
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
198
191
}
192
+ if ( ! options . chown && process . getuid ) {
193
+ options . chown = { uid : stats . uid , gid : stats . gid }
194
+ }
195
+ } catch ( ex ) {
196
+ // ignore stat errors
199
197
}
198
+ }
199
+
200
+ var fd
201
+ var cleanup = cleanupOnExit ( tmpfile )
202
+ var removeOnExitHandler = onExit ( cleanup )
203
+
204
+ try {
200
205
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 )
204
207
if ( Buffer . isBuffer ( data ) ) {
205
208
fs . writeSync ( fd , data , 0 , data . length , 0 )
206
209
} else if ( data != null ) {
@@ -215,6 +218,7 @@ function writeFileSync (filename, data, options) {
215
218
fs . renameSync ( tmpfile , filename )
216
219
removeOnExitHandler ( )
217
220
} catch ( err ) {
221
+ if ( fd ) fs . closeSync ( fd )
218
222
removeOnExitHandler ( )
219
223
cleanup ( )
220
224
throw err
0 commit comments