UNPKG

1.34 kBJavaScriptView Raw
1// try to find the most reasonable prefix to use
2
3module.exports = findPrefix
4
5var fs = require("fs")
6var path = require("path")
7
8function findPrefix (p, cb_) {
9 function cb (er, p) {
10 process.nextTick(function () {
11 cb_(er, p)
12 })
13 }
14
15 p = path.resolve(p)
16 // if there's no node_modules folder, then
17 // walk up until we hopefully find one.
18 // if none anywhere, then use cwd.
19 var walkedUp = false
20 while (path.basename(p) === "node_modules") {
21 p = path.dirname(p)
22 walkedUp = true
23 }
24 if (walkedUp) return cb(null, p)
25
26 findPrefix_(p, p, cb)
27}
28
29function findPrefix_ (p, original, cb) {
30 if (p === "/"
31 || (process.platform === "win32" && p.match(/^[a-zA-Z]:(\\|\/)?$/))) {
32 return cb(null, original)
33 }
34 fs.readdir(p, function (er, files) {
35 // an error right away is a bad sign.
36 // unless the prefix was simply a non
37 // existent directory.
38 if (er && p === original) {
39 if (er.code === "ENOENT") return cb(null, original);
40 return cb(er)
41 }
42
43 // walked up too high or something.
44 if (er) return cb(null, original)
45
46 if (files.indexOf("node_modules") !== -1
47 || files.indexOf("package.json") !== -1) {
48 return cb(null, p)
49 }
50
51 var d = path.dirname(p)
52 if (d === p) return cb(null, original)
53
54 return findPrefix_(d, original, cb)
55 })
56}