Skip to content

Commit

Permalink
(Closes #271) lib/util/utimes: properly close file descriptors in the…
Browse files Browse the repository at this point in the history
… event of an error
  • Loading branch information
hhamilto committed Oct 16, 2016
1 parent aec5548 commit 5fc1421
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 4 deletions.
41 changes: 40 additions & 1 deletion lib/util/__tests__/utimes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ var os = require('os')
var fs = require('fs')
var fse = require(process.cwd())
var semver = require('semver')
var utimes = require('../utimes')
var proxyquire = require('proxyquire')
var gracefulFsStub
var utimes

/* global beforeEach, describe, it */

Expand All @@ -17,6 +19,9 @@ describe('utimes', function () {
beforeEach(function (done) {
TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'utimes')
fse.emptyDir(TEST_DIR, done)
// reset stubs
gracefulFsStub = {}
utimes = proxyquire('../utimes', {'graceful-fs': gracefulFsStub})
})

describe('hasMillisResSync()', function () {
Expand Down Expand Up @@ -79,5 +84,39 @@ describe('utimes', function () {
done()
})
})

it('should close open file desciptors after encountering an error', function (done) {
var fakeFd = Math.random()

gracefulFsStub.open = function (pathIgnored, flagsIgnored, modeIgnored, callback) {
if (typeof modeIgnored === 'function') {
callback = modeIgnored
}
process.nextTick(function () {
callback(null, fakeFd)
})
}

var closeCalled = false
gracefulFsStub.close = function (fd, callback) {
assert.equal(fd, fakeFd)
closeCalled = true
if (callback) process.nextTick(callback)
}

var testError
gracefulFsStub.futimes = function (fd, atimeIgnored, mtimeIgnored, callback) {
process.nextTick(function () {
testError = new Error('A test error')
callback(testError)
})
}

utimes.utimesMillis('ignored', 'ignored', 'ignored', function (err) {
assert.equal(err, testError)
assert(closeCalled)
done()
})
})
})
})
7 changes: 4 additions & 3 deletions lib/util/utimes.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ function utimesMillis (path, atime, mtime, callback) {
// if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
fs.open(path, 'r+', function (err, fd) {
if (err) return callback(err)
fs.futimes(fd, atime, mtime, function (err) {
if (err) return callback(err)
fs.close(fd, callback)
fs.futimes(fd, atime, mtime, function (futimesErr) {
fs.close(fd, function (closeErr) {
if (callback) callback(futimesErr || closeErr)
})
})
})
}
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"istanbul": "^0.3.5",
"minimist": "^1.1.1",
"mocha": "^2.1.0",
"proxyquire": "^1.7.10",
"read-dir-files": "^0.1.1",
"secure-random": "^1.1.1",
"semver": "^4.3.6",
Expand Down

0 comments on commit 5fc1421

Please sign in to comment.