Post

Should you use path.resolve()

Tired of wrestling 🤼‍♂️ with hardcoded paths, battling ⚔️ portability issues, and fearing security vulnerabilities? This guide unveils the pitfalls of manual path construction and empowers you with the magic ✨ of the Node.js path module.

We’ll delve into common missteps like directory changes, platform clashes, and attack susceptibility. Then, I’ll equip you with best practices for building flexible, secure, and maintainable paths. ️

Are you writing paths like this?

1
let path = "../folder1/folder2/file.xml"

There are multiple issues with this approach

1. Changes in project directory

If you hardcode relative paths -like ./config/app.config.json and the script is executed from a different working directory, the relative path might not point to the correct location.

2. Forward slash vs Back slash

Different operating systems use different path separators (e.g., / on Unix-like systems, \ on Windows). Hardcoding separators can make code non-portable.

3. Vulnerable to attacks

Manual path construction can be prone to errors and vulnerabilities like path traversal attacks, where attackers can manipulate paths to access unauthorized files or directories.

4. Hard to maintain

Hardcoded paths can make code less readable and harder to maintain, especially in large projects with complex folder structures.

5. Difficult to make paths

You will miss out on multiple utilities in path module such as joining paths, normalizing paths, extracting path components, and more.

Wrong Way

1
2
let configPath = './dir/config';
console.log(configPath);

Right Way

1
2
3
4
5
let path = require('path');
let base = path.resolve(__dirname);
let configDir = 'config';
let configPath = path.resolve(base, configDir);
let configFile = path.join(configPath, 'app.config.json');
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.