0
0
Node.jsframework~5 mins

path.join for cross-platform paths in Node.js

Choose your learning style9 modes available
Introduction
Use path.join to combine file or folder names into a single path that works on any computer system.
When you need to create a file path that works on Windows, Mac, or Linux.
When combining folder names and file names into one path.
When you want to avoid errors caused by wrong slashes in file paths.
When writing code that others will run on different operating systems.
When building file paths dynamically from variables.
Syntax
Node.js
const path = require('path');
const fullPath = path.join(part1, part2, ..., partN);
Each part is a string representing a folder or file name.
path.join automatically adds the correct slash between parts.
Examples
Joins 'folder' and 'file.txt' into a path like 'folder/file.txt' or 'folder\file.txt' depending on the system.
Node.js
const path = require('path');
const fullPath = path.join('folder', 'file.txt');
console.log(fullPath);
Joins multiple parts into one path with correct separators.
Node.js
const path = require('path');
const fullPath = path.join('folder', 'subfolder', 'file.txt');
console.log(fullPath);
If the first part starts with a slash, the path is absolute starting from root.
Node.js
const path = require('path');
const fullPath = path.join('/root', 'folder', 'file.txt');
console.log(fullPath);
Sample Program
This program joins three parts into one path that works on any OS. It prints the combined path.
Node.js
const path = require('path');

const folder = 'documents';
const subfolder = 'photos';
const filename = 'image.png';

const fullPath = path.join(folder, subfolder, filename);
console.log(fullPath);
OutputSuccess
Important Notes
path.join uses the correct slash for your operating system automatically.
Avoid manually adding slashes when building paths; use path.join instead.
If any part is an absolute path, path.join resets the path from that part.
Summary
path.join combines parts of a path safely for any OS.
It prevents errors from wrong slashes or missing separators.
Use it whenever you build file or folder paths in Node.js.