pkg-dir用于查找指定工作目录(cwd)中最近的 package.json
文件并返回其目录路径。
安装:
npm install pkg-dir
官方使用示例:
const pkgDir = require('pkg-dir');
(async () => {
const rootDir = await pkgDir(__dirname);
console.log(rootDir);
//=> '/Users/sindresorhus/foo'
})();
废话不说,上源码:
'use strict';
const path = require('path');
const findUp = require('find-up');
const pkgDir = async cwd => {
const filePath = await findUp('package.json', {cwd});
return filePath && path.dirname(filePath);
};
module.exports = pkgDir;
// TODO: Remove this for the next major release
module.exports.default = pkgDir;
module.exports.sync = cwd => {
const filePath = findUp.sync('package.json', {cwd});
return filePath && path.dirname(filePath);
};
-
'use strict' :启用严格模式。这一模式会使得一些常见的错误在代码运行时被捕捉到,有助于提高代码的安全性和可维护性。
-
const path = require('path') :引入 Node.js 的
path
模块,用于处理和转换文件路径。 -
const findUp = require('find-up') :引入一个名为
find-up
的模块,主要用于从当前目录向上查找指定的文件(例如package.json
)。 -
const pkgDir = async cwd => {...} :定义了一个异步箭头函数
pkgDir
,接受一个参数cwd
(当前工作目录)。该函数的功能是查找package.json
文件并返回其目录。- const filePath = await findUp('package.json', {cwd}) :使用
findUp
方法查找cwd
目录及其上层目录中最近的package.json
文件,并将其路径赋值给filePath
。 - return filePath && path.dirname(filePath) :如果找到了
filePath
,则返回该文件的目录;如果没有找到,则返回undefined
。
- const filePath = await findUp('package.json', {cwd}) :使用
-
module.exports = pkgDir :将
pkgDir
函数导出,以便其他模块可以使用。 -
// TODO: Remove this for the next major release:注释,表明在下一个主要版本中将删除某些功能或代码。
-
module.exports.default = pkgDir; :将
pkgDir
函数作为默认导出,这样可以通过不同的方式导入。 -
module.exports.sync = cwd => {...}; :定义一个同步版本的
pkgDir
函数sync
,同样接受cwd
作为参数。- const filePath = findUp.sync('package.json', {cwd}); :使用
findUp.sync
方法同步查找package.json
文件。 - return filePath && path.dirname(filePath); :与异步版本相同,返回找到的文件目录或
undefined
。
- const filePath = findUp.sync('package.json', {cwd}); :使用
总的来说,这段代码定义了一个模块,提供了查找 package.json
文件的异步和同步方法,便于使用者获取项目的根目录。