简体   繁体   English

Node.js路径:解析相对路径

[英]Node.js path: Resolve relative paths

Given this folder structure: 给定此文件夹结构:

content/
  folder/
    1.md
    2.md

and the Node.js process running in the root of the structure. 并且Node.js进程在结构的根目录中运行。

I have these pieces of information available: 我有以下可用的信息:

// path to the content folder
const dir = 'content'; 

// path to the current file
const filepath = 'folder/1.md';

// A link relative to the current file
const href = './2.md';

Which combination of Node.js path methods will give me the result folder/2.md ? 哪种Node.js path方法组合会给我结果folder/2.md I want to resolve the relative href to a path in the content folder. 我想将相对href解析为内容文件夹中的路径。

I think I'm missing something obvious, but I can't figure it out for the life of me. 我想我缺少明显的东西,但是我无法终生解决。

PS : The larger context is that I'm working on a static site generator and would like to replace in the Markdown any relative links to other Markdown documents with their URL, and for that I need a href relative to the content folder to look it up. PS :更大的上下文是我正在使用静态网站生成器,并希望在Markdown中用其URL替换指向其他Markdown文档的任何相对链接,为此,我需要相对于内容文件夹的href来查找它起来

I think this is what you are looking for, 我想这就是你要找的

const path = require("path");

const filepath = "folder/1.md";
const href = "./2.md";

console.log(path.join(path.dirname(filepath), href)); // folder/2.md

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM