EN
Node.js - get relative path to indicated path
0 points
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:
xxxxxxxxxx
1
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:
xxxxxxxxxx
1
const path = require('path');
2
3
// example paths
4
const from = 'projects\\app\\src';
5
const to = 'projects\\app\\resources\\background.png';
6
7
const result = path.relative(from, to);
8
9
console.log(result); // ..\resources\background.png
Output:
xxxxxxxxxx
1
..\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:
xxxxxxxxxx
1
const path = require('path');
2
3
// example paths
4
const from = 'projects\\app\\src';
5
const to = 'projects\\app\\resources';
6
7
const result = path.relative(from, to);
8
9
console.log(result); // ..\resources
Output:
xxxxxxxxxx
1
..\resources
Note:
Thanks to the path we got, we are able to access the resources directory in the src folder.