Dan Inactive
Dan Inactive

Reputation: 10060

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.

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? I want to resolve the relative href to a path in the content folder.

I think I'm missing something obvious, but I can't figure it out for the life of me.

P.S.: 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.

Upvotes: 0

Views: 1984

Answers (1)

Ramaraja
Ramaraja

Reputation: 2626

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

Upvotes: 1

Related Questions