/

Node File Paths - Manipulating and Interacting with Paths in Node

Node File Paths - Manipulating and Interacting with Paths in Node

In Node, working with file paths is essential for many applications. However, there are differences between file paths on different operating systems that must be taken into account. In this article, we will explore how to interact with and manipulate file paths in Node.

Getting information out of a path

To extract information from a file path, Node provides several useful methods:

  • dirname: Returns the parent folder of a file.
  • basename: Returns the filename part of a path.
  • extname: Returns the file extension.

Here’s an example of how to use these methods:

1
2
3
4
5
6
7
const path = require('path');

const filePath = '/users/flavio/notes.txt';

path.dirname(filePath); // Returns: /users/flavio
path.basename(filePath); // Returns: notes.txt
path.extname(filePath); // Returns: .txt

By providing a second argument to basename, you can get the file name without the extension:

1
path.basename(filePath, path.extname(filePath)); // Returns: notes

Working with paths

Node provides the path.join() method to join multiple parts of a path:

1
2
3
4
5
const path = require('path');

const name = 'flavio';

path.join('/', 'users', name, 'notes.txt'); // Returns: /users/flavio/notes.txt

To obtain the absolute path calculation of a relative path, you can use the path.resolve() method:

1
2
3
const path = require('path');

path.resolve('flavio.txt'); // Returns the absolute path, e.g., /Users/flavio/flavio.txt (if run from the home folder)

If you provide a second parameter to resolve, it will use the first parameter as the base for the second:

1
2
3
const path = require('path');

path.resolve('tmp', 'flavio.txt'); // Returns the absolute path, e.g., /Users/flavio/tmp/flavio.txt (if run from the home folder)

If the first parameter starts with a slash, it denotes an absolute path:

1
2
3
const path = require('path');

path.resolve('/etc', 'flavio.txt'); // Returns: /etc/flavio.txt

Another useful function provided by Node is path.normalize(), which attempts to calculate the actual path when it contains relative specifiers like . or .., or double slashes:

1
2
3
const path = require('path');

path.normalize('/users/flavio/..//test.txt'); // Returns: /users/test.txt

It is important to note that both resolve and normalize do not check if the path exists; they simply perform calculations based on the given information.

Tags: Node.js, file paths, path manipulation, path joining, path normalization, basename, dirname, extname