EN
TypeScript / Node.js - resolve path
3 points
In this article, we would like to show you how to resolve path in Node.js.
Quick solution:
xxxxxxxxxx
1
import * as path from 'path';
2
3
const absolutePath: string = path.resolve('public/images', 'logo.png');
Note:
The
resolve()
method will return the absolute path according to the current working directory and operating system (Windows, Linux, etc.).
In this example, we use path.resolve()
method that resolves the specified paths into an absolute path.
Let's suppose we have the following directory structure:
xxxxxxxxxx
1
C:\
2
├───Project
3
│ └───Scripts
4
│ └───index.js
5
...
index.js
file contains:
xxxxxxxxxx
1
import * as path from 'path';
2
3
console.log('CURRENT SCRIPT DIRECTORY: ' + __dirname); // prints the script location directory path
4
console.log('CURRENT WORKING DIRECTORY: ' + path.resolve()); // prints the directory path from where script was run
5
6
const path1: string = path.resolve('/public/images', 'logo.png');
7
const path2: string = path.resolve('public/images', 'logo.png');
8
const path3: string = path.resolve('public', 'images', 'logo.png');
9
10
console.log('PATH 1: ' + path1);
11
console.log('PATH 2: ' + path2);
12
console.log('PATH 3: ' + path3);
Go to C:\Project\
and run index.js
file using:
xxxxxxxxxx
1
node ./Scripts/index.js
Output:
xxxxxxxxxx
1
CURRENT SCRIPT DIRECTORY: C:\Project\Scripts
2
CURRENT WORKING DIRECTORY: C:\Project
3
PATH 1: C:\public\images\logo.png
4
PATH 2: C:\Project\public\images\logo.png
5
PATH 3: C:\Project\public\images\logo.png