6.find-up库的源码解析
该库用于在某个目录下向上找指定文件
找到返回该文件路径,找不到返回null
- 同步的使用
const findUp = require("find-up")
const fp = findUp.sync('package.json', {cwd: "a/b/c/d"});
- 同步的源码
const path = require('path');
const locatePath = require('locate-path');
module.exports.sync = (filename, opts) => {
opts = opts || {};
let dir = path.resolve(opts.cwd || '');
// 获取根路径,如果根路径都还没找到,那么就是没找到,返回null
const root = path.parse(dir).root;
const filenames = [].concat(filename);
// 写了一个死循环,通过dir = path.dirname(dir)一级级往上找,找到就返回,如果到dir与根路径root一样还没找到,就返回null
while (true) {
const file = locatePath.sync(filenames, {cwd: dir});
if (file) {
return path.join(dir, file);
} else if (dir === root) {
return null;
}
dir = path.dirname(dir);
}
};
- 同步方法源码知识点
- while死循环要注意打破的条件,一般通过以下方法打破:
- return
- break
path.parse(路径)
- 返回:
root
根路径dir
父文件夹路径base
最后一级路径ext
后缀,文件有后缀,文件夹没后缀为空字符串name
最后一级的文件名(不带后缀)或文件夹名
- 举例:
path.parse("/a/b/c.js")
- 答案:
{ root: '/', dir: '/a/b', base: 'c.js', ext: '.js', name: 'c' }
- 答案:
- 返回:
- while死循环要注意打破的条件,一般通过以下方法打破: