Skip to content

Commit

Permalink
refactor(*): use ES2015, allow custom cwd to be passed through options
Browse files Browse the repository at this point in the history
BREAKING CHANGE: default export is async and returns a promise; allow custom cwd to be passed

through opts.cwd; pass opts.local to check if package exists locally.
  • Loading branch information
tunnckoCore committed Dec 11, 2016
1 parent aaedf01 commit a9586e7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
44 changes: 43 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,48 @@

'use strict'

module.exports = function detectInstalled () {
const fs = require('fs')
const path = require('path')
const modules = require('global-modules')

module.exports = function detectInstalled (name, opts) {
return new Promise((resolve, reject) => {
if (!isValidString(name)) {
const message = 'detect-installed: expect `name` to be string'
return reject(new TypeError(message))
}

fs.stat(defaults(name, opts), (err, stats) => {
if (err) return reject(err)
resolve(stats.isDirectory())
})
})
}

module.exports.sync = function detectInstalledSync (name, opts) {
if (!isValidString(name)) {
throw new TypeError('detect-installed: expect `name` to be string')
}
return tryStatSync(defaults(name, opts))
}

const isValidString = (val) => {
return typeof val === 'string' ? val.length > 0 : false
}

const defaults = (name, opts) => {
opts = opts && typeof opts === 'object' ? opts : {}
opts.cwd = typeof opts.cwd === 'string' ? opts.cwd : process.cwd()

return opts.local
? path.join(opts.cwd, 'node_modules', name)
: path.join(modules, name)
}

const tryStatSync = (fp) => {
try {
return fs.statSync(fp).isDirectory()
} catch (err) {
return false
}
}
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
"precommit": "git add --all",
"commit": "git-cz"
},
"dependencies": {},
"dependencies": {
"global-modules": "^0.2.3"
},
"devDependencies": {
"commitizen": "^2.8.6",
"coveralls": "^2.11.15",
Expand Down Expand Up @@ -68,4 +70,4 @@
"node": ">=4",
"npm": ">=3"
}
}
}

0 comments on commit a9586e7

Please sign in to comment.