0
0
Node.jsframework~5 mins

path.resolve for absolute paths in Node.js

Choose your learning style9 modes available
Introduction

We use path.resolve to get the full absolute path from relative parts. It helps find the exact location of files or folders on your computer.

When you want to find the full path of a file starting from your current folder.
When combining folder names and file names to get one complete path.
When you need to avoid mistakes caused by relative paths like './' or '../'.
When writing scripts that work on any computer regardless of where they run.
When you want to make sure your program uses the correct file location.
Syntax
Node.js
path.resolve([from ...], to)

You can give one or more path parts as arguments.

The function joins them and returns the absolute path.

Examples
This joins 'folder' and 'file.txt' and returns the absolute path.
Node.js
const path = require('path');

const fullPath = path.resolve('folder', 'file.txt');
console.log(fullPath);
This resolves the path by moving up one folder from '/home/user' then into 'docs/readme.md'.
Node.js
const path = require('path');

const fullPath = path.resolve('/home/user', '../docs', 'readme.md');
console.log(fullPath);
Calling path.resolve with no arguments returns the current working directory.
Node.js
const path = require('path');

const fullPath = path.resolve();
console.log(fullPath);
Sample Program

This program uses path.resolve to get the full absolute path to the file Button.js inside src/components. It prints the full path so you can see exactly where the file is on your computer.

Node.js
const path = require('path');

// Combine parts to get absolute path
const absolutePath = path.resolve('src', 'components', 'Button.js');

console.log('Absolute path:', absolutePath);
OutputSuccess
Important Notes

Note: The exact output depends on your current folder when you run the code.

Tip: Use path.resolve to avoid errors with relative paths.

Summary

path.resolve creates a full absolute path from parts.

It helps your program find files correctly no matter where it runs.

Use it to combine folder and file names safely.