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:
import * as path from 'path';
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.).
Practical example
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:
C:\
├───Project
│ └───Scripts
│ └───index.js
...
index.js file contains:
import * as path from 'path';
console.log('CURRENT SCRIPT DIRECTORY: ' + __dirname); // prints the script location directory path
console.log('CURRENT WORKING DIRECTORY: ' + path.resolve()); // prints the directory path from where script was run
const path1: string = path.resolve('/public/images', 'logo.png');
const path2: string = path.resolve('public/images', 'logo.png');
const path3: string = path.resolve('public', 'images', 'logo.png');
console.log('PATH 1: ' + path1);
console.log('PATH 2: ' + path2);
console.log('PATH 3: ' + path3);
Go to C:\Project\ and run index.js file using:
node ./Scripts/index.js
Output:
CURRENT SCRIPT DIRECTORY: C:\Project\Scripts
CURRENT WORKING DIRECTORY: C:\Project
PATH 1: C:\public\images\logo.png
PATH 2: C:\Project\public\images\logo.png
PATH 3: C:\Project\public\images\logo.png