Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@milsosa
Last active August 27, 2015 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milsosa/d811799a4660c44400f7 to your computer and use it in GitHub Desktop.
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.
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