Languages
[Edit]
EN

TypeScript / Node.js - resolve path

3 points
Created by:
Mahir-Bright
1311

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

 

See also

  1. TypeScript / Node.js - install Node types (type declarations)

  2. Node.js - resolve path

References

  1. Path | Node.js v16.9.0 Documentation

Alternative titles

  1. TypeScript / Node.js - safe way to add path to path (resolve path)
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