Repository: jprichardson/node-fs-extra (js)

Issue:
ensureFileSync vs ensureDirSync
When `ensureDirSync` is called on a folder that already exists as a file, `EEXIST` is thrown as expected.

When `ensureFileSync` is called on a file that already exists as a folder nothing is thrown.

Should not the two behaviours be the same? IMHO either both should throw or none of them should throw.

Pull request description:
ensureFile & ensureFileSync should error when the path is a directory
Fixes #465 

If testing locally, make sure to run `npm update` first; I discovered a bug in universalify while working on this that has been fixed in the latest patch release of universalify.

Patch:
diff --git a/lib/ensure/file.js b/lib/ensure/file.js
index 962c21c..67eed30 100644
--- a/lib/ensure/file.js
+++ b/lib/ensure/file.js
@@ -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)
@@ -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)) {


Test patch:
diff --git a/lib/ensure/__tests__/ensure.test.js b/lib/ensure/__tests__/ensure.test.js
index b7b519e..0c06597 100644
--- a/lib/ensure/__tests__/ensure.test.js
+++ b/lib/ensure/__tests__/ensure.test.js
@@ -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()', () => {
@@ -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()', () => {