EN
TypeScript / 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. Install node types with the following command:
xxxxxxxxxx
1
npm install --save @types/node
2. Import path
module using:
xxxxxxxxxx
1
import * as path from 'path';
3. 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
import * as path from 'path';
2
3
// example paths
4
const from: string = 'projects\\app\\src';
5
const to: string = 'projects\\app\\resources\\background.png';
6
7
const result: string = 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
import * as path from 'path';
2
3
// example paths
4
const from: string = 'projects\\app\\src';
5
const to: string = 'projects\\app\\resources';
6
7
const result: string = 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.