1 |
|
2 |
|
3 | module.exports = findPrefix
|
4 |
|
5 | var fs = require("fs")
|
6 | var path = require("path")
|
7 |
|
8 | function 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 |
|
17 |
|
18 |
|
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 |
|
29 | function 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 |
|
36 |
|
37 |
|
38 | if (er && p === original) {
|
39 | if (er.code === "ENOENT") return cb(null, original);
|
40 | return cb(er)
|
41 | }
|
42 |
|
43 |
|
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 | }
|