-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
findPackage.js
72 lines (69 loc) · 2.02 KB
/
findPackage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Find package folder
const fs = require("fs");
const findit = require("findit2");
const path = require("path");
const relative = require("relative");
const findPackage = function (packageName, searchPath) {
return new Promise((resolve, reject) => {
try {
searchPath = path.resolve(process.cwd(), searchPath);
} catch (err) {
reject("searchPath does not exist");
}
const finder = findit(searchPath);
// eslint-disable-next-line no-unused-vars
finder.on("file", (file, stat, stop) => {
const basename = path.basename(file);
if (basename == "package.json") {
const dirname = relative(process.cwd(), path.dirname(file));
let pkg = null;
try {
pkg = require(path.join(file));
} catch (err) {
return;
}
if (pkg.name != packageName) {
console.debug(
`Mismatched package name in ${path.join(dirname, basename)}: actual=${pkg.name}, expected=${packageName}`
);
return;
}
console.debug(`Found package name in ${path.join(dirname, basename)}`);
finder.stop();
resolve({ dirname, pkg, file });
}
});
finder.on("end", () => {
resolve(null);
});
finder.on("error", () => {
finder.stop();
reject("find package.json error");
});
});
};
if (require.main === module) {
if (process.argv.length < 5) {
console.log(
"Usage: node findPackage.js <pkg-name> <search-path> <output-filename>"
);
process.exit(1);
} else {
findPackage(process.argv[2], process.argv[3])
.then((result) => {
if (result) {
// Write to output file
const outputFilename = process.argv[4];
const content = JSON.stringify(result);
try {
fs.writeFileSync(outputFilename, content);
console.log("Saved to " + outputFilename);
} catch (err) {
console.error(err);
}
}
})
.catch(() => {});
}
}
module.exports = { findPackage };