Languages
[Edit]
EN

Node.js - get relative path to indicated path

0 points
Created by:
Nathanial-Donald
374

In this article, we would like to show you how to get a relative path from one location to anotherĀ inĀ Node.js.

1. ImportĀ pathĀ module using:

const path = require('path');

2. UseĀ path.relative()Ā method to get the relative path from from to to based on the current working directory.

Relative path to file:

const path = require('path');

// example paths
const from = 'projects\\app\\src';
const to = 'projects\\app\\resources\\background.png';

const result = path.relative(from, to);

console.log(result); // ..\resources\background.png

Output:

..\resources\background.png

Note:

Thanks to the path we got, we are able to access the background.png file in the src folder.

Relative path to directory:

const path = require('path');

// example paths
const from = 'projects\\app\\src';
const to = 'projects\\app\\resources';

const result = path.relative(from, to);

console.log(result); // ..\resources

Output:

..\resources

Note:

Thanks to the path we got, we are able to access the resources directory in the src folder.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join