Last active
August 27, 2015 21:54
-
-
Save milsosa/d811799a4660c44400f7 to your computer and use it in GitHub Desktop.
[Node.js] Finds the pathname of the parent module's package descriptor file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var path = require('path'); | |
/** | |
* Finds the pathname of the parent module's package descriptor file. If the | |
* directory is undefined (the default case), then it is set to the directory | |
* name of the parent module's filename. If no package.json file is found, then | |
* the parent directories are recursively searched until the file is found or | |
* the root directory is reached. Returns the pathname if found or null if not. | |
*/ | |
function findParentPkgDesc(directory) { | |
if (!directory) { | |
directory = path.dirname(module.parent.filename); | |
} | |
var file = path.resolve(directory, 'package.json'); | |
if (fs.existsSync(file) && fs.statSync(file).isFile()) { | |
return file; | |
} | |
var parent = path.resolve(directory, '..'); | |
if (parent === directory) { | |
return null; | |
} | |
return findParentPkgDesc(parent); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment