Working with paths using join, resolve, and filename extraction
🎯 Introduction
By the end of this article, you will be able to combine file paths, extract filenames, and distinguish the working directory from the module directory.
🧱 path follows operating system path rules
node:path is Node.js's built-in path module. It computes path strings; it does not create files or check whether a result exists.
Create paths.mjs with this import. Append the following examples one at a time and run node paths.mjs to inspect them:
import path from 'node:path'
Absolute path results below use macOS/Linux conventions. On Windows, a typical absolute path looks like C:\work\demo\note.txt; actual output follows the relevant system's rules.
🧩 join: combine path segments
When directories and filenames come from separate variables, use join rather than handling path separators yourself:
console.log(path.join('data', 'note.txt'))
This prints data/note.txt on macOS/Linux and data\note.txt on Windows. The return value is a path string. Since the input has no absolute starting point, the result is still relative.
join also normalizes the path:
console.log(path.join('data', '..', 'note.txt'))
This prints note.txt.
📍 resolve: obtain a complete absolute path
Use resolve when you need to show exactly where a program will operate:
console.log(path.resolve('data', 'note.txt'))
If the terminal's current directory is /work/demo, the result is /work/demo/data/note.txt. process.cwd() returns that current directory. Starting from another location changes the result.
resolve processes paths from right to left, using an absolute path as the starting point when it encounters one:
console.log(path.resolve('/work', '/tmp', 'note.txt'))
On macOS/Linux this prints /tmp/note.txt; the preceding /work is ignored.
Use join to combine segments and resolve to determine an absolute location. They are not always interchangeable ways to concatenate paths.
🏷️ Extract filenames and extensions
Use basename to display a name without its directory:
console.log(path.basename('data/note.txt'))
The result is note.txt, including the extension.
Use extname for simple classification by extension:
console.log(path.extname('data/note.txt'))
The result is .txt, including the dot. A name without an extension returns an empty string. An extension is only part of a name; it cannot prove the actual content type.
Use parse to retrieve all the components at once:
console.log(path.parse('data/note.txt'))
The result contains root: '', dir: 'data', base: 'note.txt', ext: '.txt', and name: 'note': the root, directory, full filename, extension, and filename without its extension. The root is empty because the input is relative.
🪤 Read bundled configuration from any starting directory
Locate configuration bundled with a script relative to the script, rather than the terminal's current directory. For example, a file-list generation script needs a configuration file beside it. Whether you run it from the project root or its own directory, it should read the same configuration.
Prepare these two files in your project:
project/
└── scripts/
├── read-config.mjs
└── config.json
Set the configuration contents to:
{
"outputDir": "dist"
}
outputDir is where the generated list will be saved. For now, only verify that the configuration can be read; do not generate the list yet.
A relative path changes its target with the starting directory
Save this as scripts/read-config.mjs:
import { readFileSync } from 'node:fs'
console.log(readFileSync('./config.json', 'utf8'))
This introduces readFileSync from the next article: it reads the specified file, and utf8 returns text. Focus on how these two launch methods differ:
| Terminal directory | Command | Lookup location and result |
|---|---|---|
project/scripts | node read-config.mjs | Reads scripts/config.json and prints its text |
project | node scripts/read-config.mjs | Looks for config.json in the root and reports ENOENT if it is missing |
The script has not moved; the terminal directory has changed. When readFileSync receives a relative path string, it starts from process.cwd(). Using path.resolve('./config.json') still depends on that same starting point.
Resolve from the script to make the result independent of how it starts
Replace the script with:
import { readFileSync } from 'node:fs'
const configUrl = new URL('./config.json', import.meta.url)
console.log(readFileSync(configUrl, 'utf8'))
import.meta.url identifies the current read-config.mjs, so configUrl always points to the configuration beside it. File APIs accept this URL object directly.
Run both commands from the table again. Both print the configuration text containing "outputDir": "dist".
Use the module location for configuration, templates, and other files bundled with a script. Use the working directory when processing files in the user's current directory. Choose according to what the file belongs to; not every relative path needs rewriting.
❓ Questions and answers
Q1: How do I choose between join and resolve?
Use join to combine directories and filenames, and resolve to obtain an absolute path. Neither creates files or checks whether they exist.
Q2: Why does reading fail when I run from another directory?
Relative file API paths start from the working directory. Locate bundled files using import.meta.url.
Q3: What if a filename has no extension?
extname returns an empty string. This does not mean the file is missing.
🧪 Exercise
Use join to combine logs and app.log, then print its absolute path, filename, and extension.
// Write your code here
🎉 Try these techniques with your own examples!
