Node.js 在节点js中查找包含文件的父文件夹
我希望能够通过将Node.js 在节点js中查找包含文件的父文件夹,node.js,path,Node.js,Path,我希望能够通过将startingPoint.txt的路径传递给节点JS中的函数来查找target.json,给定以下文件夹结构: - root - sub1 - sub2 startingPoint.txt target.json 我为它找到了一个名为find-up的节点包,但这可能需要不超过6行代码 以下是我目前拥有的: import { join, dirname } from 'path'; import { existsSync } from 'fs'; expor
startingPoint.txt
的路径传递给节点JS中的函数来查找target.json
,给定以下文件夹结构:
- root
- sub1
- sub2
startingPoint.txt
target.json
我为它找到了一个名为find-up
的节点包,但这可能需要不超过6行代码
以下是我目前拥有的:
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, "../");
}
}
我知道这个老问题,但我刚刚实现了类似的东西,花了很多时间试图找到一个好的解决方案 因此,对于未来的探索者,这里是我使用path和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:\path\to\start\at";
let target_file = "findme.txt";
console.log(findInPathAncestry(start_location, target_file));
// expected output:
// C:\path\to\findme.txt
// or false if file doesn't exist in path
通过使用PATH.normalize和PATH.sep,可以在windows和unix环境中执行此操作
// example file structure:
// C:\
// | - path\
// | --- to\
// | ----- start\
// | ------- at\
// | ----- findme.txt
let start_location = "C:\path\to\start\at";
let target_file = "findme.txt";
console.log(findInPathAncestry(start_location, target_file));
// expected output:
// C:\path\to\findme.txt
// or false if file doesn't exist in path