Skip to content

Commit

Permalink
ensureFile & ensureFileSync should error when the path is a directory
Browse files Browse the repository at this point in the history
Fixes #465
  • Loading branch information
RyanZim committed Jul 20, 2017
1 parent 28b7cfe commit 3fc5894
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
29 changes: 29 additions & 0 deletions lib/ensure/__tests__/ensure.test.js
Expand Up @@ -45,6 +45,19 @@ describe('fs-extra', () => {
})
})
})

describe('> when there is a directory at that path', () => {
it('should error', done => {
const p = path.join(TEST_DIR, 'somedir')
fs.mkdirSync(p)

fse.ensureFile(p, err => {
assert(err)
assert.equal(err.code, 'EISDIR')
done()
})
})
})
})

describe('+ ensureFileSync()', () => {
Expand All @@ -68,6 +81,22 @@ describe('fs-extra', () => {
assert(fs.existsSync(file))
})
})

describe('> when there is a directory at that path', () => {
it('should error', () => {
const p = path.join(TEST_DIR, 'somedir2')
fs.mkdirSync(p)

assert.throws(() => {
try {
fse.ensureFileSync(p)
} catch (e) {
assert.equal(e.code, 'EISDIR')
throw e
}
})
})
})
})

describe('+ ensureDir()', () => {
Expand Down
11 changes: 7 additions & 4 deletions lib/ensure/file.js
Expand Up @@ -14,9 +14,8 @@ function createFile (file, callback) {
})
}

pathExists(file, (err, fileExists) => {
if (err) return callback(err)
if (fileExists) return callback()
fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
if (!err && stats.isFile()) return callback()
const dir = path.dirname(file)
pathExists(dir, (err, dirExists) => {
if (err) return callback(err)
Expand All @@ -30,7 +29,11 @@ function createFile (file, callback) {
}

function createFileSync (file) {
if (fs.existsSync(file)) return
let stats
try {
stats = fs.statSync(file)
} catch (e) {}
if (stats && stats.isFile()) return

const dir = path.dirname(file)
if (!fs.existsSync(dir)) {
Expand Down

0 comments on commit 3fc5894

Please sign in to comment.