在节点 js 中查找包含文件的父文件夹



我希望能够通过传递路径来找到target.jsonstartingPoint.txt中的函数,给定以下文件夹结构:

- root
- sub1
- sub2
startingPoint.txt
target.json

我为它找到了一个名为find-up的节点包,但这种事情可能需要不超过 6 行代码。


export function findUp(start: Path, target: string): Path | undefined {
// this code here
}
const pathToTarget = findUp("root/sub1/sub2/startingPoint.txt", "target.json"/);
console.log(pathToTarget); // "root/target.json"

我知道的老问题,但我不得不实现类似的东西,并花了很长时间试图找到一个好的解决方案。

因此,对于未来的探索者,这是我使用路径和 fs 模块的解决方案。

const PATH = require('path');
const FS   = require('fs');
function findInPathAncestry(path, target) {
let current_directory_path = PATH.normalize(path).split(PATH.sep);
let result = false;
while(current_directory_path.length && !result) {
let current_path = current_directory_path.join(PATH.sep)+PATH.sep+target;
if(FS.existsSync(current_path)) {
result = current_path;
}
current_directory_path.pop();
}
return result;
}

使用示例:

// example file structure:
// C:
// | - path
// | --- to
// | ----- start
// | ------- at
// | ----- findme.txt

let start_location = "C:pathtostartat";
let target_file    = "findme.txt";
console.log(findInPathAncestry(start_location, target_file));
// expected output:
// C:pathtofindme.txt
// or false if file doesn't exist in path

使用PATH.normalize和PATH.sep允许它在Windows和Unix环境中工作。

https://nodejs.org/api/path.html#path_path_sep

这是我现在所拥有的:

import { join, dirname } from 'path';
import { existsSync } from 'fs';
export let MAX_BACK_STEPS = 50;
export function findUp(start: string, target: string, boundary?: {
path: string,
inclusive: boolean,
}): string | null {
let currentDir = dirname(start);
let lastTry = false;
let backSteps = 0;
while (backSteps++) {
if (backSteps >= MAX_BACK_STEPS) {
console.error("Too many back steps");
return null;
}
if (boundary && boundary.path.includes(currentDir)) {
if (boundary.inclusive && lastTry === false) {
lastTry = true;
} else {
return null;
}
}
const targetTestPath = join(currentDir, target);
if (existsSync(targetTestPath)) {
return targetTestPath;
}
currentDir = join(currentDir, "../");
}
}

相关内容

  • 没有找到相关文章

最新更新