1、pkg-dir
'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 releasemodule.exports.default = pkgDir;module.exports.sync = cwd => { //该库用于在某个目录下向上找指定文件,找到返回该文件路径,找不到返回null //接收两个参数 第一要寻找的文件,第二个 路径 const filePath = findUp.sync('package.json', {cwd}); return filePath && path.dirname(filePath);};
2、find-up
'use strict';const path = require('path');const locatePath = require('locate-path');const pathExists = require('path-exists');const stop = Symbol('findUp.stop');module.exports = async (name, options = {}) => { let directory = path.resolve(options.cwd || ''); const {root} = path.parse(directory); const paths = [].concat(name); const runMatcher = async locateOptions => { if (typeof name !== 'function') { return locatePath(paths, locateOptions); } const foundPath = await name(locateOptions.cwd); if (typeof foundPath === 'string') { return locatePath([foundPath], locateOptions); } return foundPath; }; // eslint-disable-next-line no-constant-condition while (true) { // eslint-disable-next-line no-await-in-loop const foundPath = await runMatcher({...options, cwd: directory}); if (foundPath === stop) { return; } if (foundPath) { return path.resolve(directory, foundPath); } if (directory === root) { return; } directory = path.dirname(directory); }};module.exports.sync = (name, options = {}) => { let directory = path.resolve(options.cwd || ''); const {root} = path.parse(directory); const paths = [].concat(name); //运行匹配器 const runMatcher = locateOptions => { if (typeof name !== 'function') { //当前库的作用就是判断某个文件名称(带后缀)数组中是否有一个文件是否在某个目录下, //如果在,则返回这个文件名称(带后缀),如果不在则返回undefined return locatePath.sync(paths, locateOptions); } const _l=locateOptions const foundPath = name(locateOptions.cwd); if (typeof foundPath === 'string') { return locatePath.sync([foundPath], locateOptions); } return foundPath; }; // eslint-disable-next-line no-constant-condition while (true) { const foundPath = runMatcher({...options, cwd: directory}); if (foundPath === stop) { return; } if (foundPath) { //如果foundPath存在,返回相对路径 return path.resolve(directory, foundPath); } if (directory === root) { return; } directory = path.dirname(directory); }};module.exports.exists = pathExists;module.exports.sync.exists = pathExists.sync;module.exports.stop = stop;