UNPKG

1.77 kBJavaScriptView Raw
1'use strict';
2
3var path = require('path')
4 , fs = require('fs');
5
6/**
7 * Attempt to somewhat safely parse the JSON.
8 *
9 * @param {String} data JSON blob that needs to be parsed.
10 * @returns {Object|false} Parsed JSON or false.
11 * @api private
12 */
13function parse(data) {
14 data = data.toString('utf-8');
15
16 //
17 // Remove a possible UTF-8 BOM (byte order marker) as this can lead to parse
18 // values when passed in to the JSON.parse.
19 //
20 if (data.charCodeAt(0) === 0xFEFF) data = data.slice(1);
21
22 try { return JSON.parse(data); }
23 catch (e) { return false; }
24}
25
26/**
27 * Find package.json files.
28 *
29 * @param {String|Object} root The root directory we should start searching in.
30 * @returns {Object} Iterator interface.
31 * @api public
32 */
33module.exports = function find(root) {
34 root = root || process.cwd();
35 if (typeof root !== "string") {
36 if (typeof root === "object" && typeof root.filename === 'string') {
37 root = root.filename;
38 } else {
39 throw new Error("Must pass a filename string or a module object to finder");
40 }
41 }
42 return {
43 /**
44 * Return the parsed package.json that we find in a parent folder.
45 *
46 * @returns {Object} Value, filename and indication if the iteration is done.
47 * @api public
48 */
49 next: function next() {
50 if (root.match(/^(\w:\\|\/)$/)) return {
51 value: undefined,
52 filename: undefined,
53 done: true
54 };
55
56 var file = path.join(root, 'package.json')
57 , data;
58
59 root = path.resolve(root, '..');
60
61 if (fs.existsSync(file) && (data = parse(fs.readFileSync(file)))) {
62 data.__path = file;
63
64 return {
65 value: data,
66 filename: file,
67 done: false
68 };
69 }
70
71 return next();
72 }
73 };
74};