Skip to main content

Working with File Paths

In Node.js, working with file paths is a common task that developers often encounter. The Node.js path module provides many helpful methods when working with file and directory paths.

To use the path module, you need to import it into your program using the require function. Here's how you can do it:

const path = require('path');

Now, you can access all the methods available in the path module.

Normalizing a Path

The path.normalize() method can be used to resolve .., . and double slashes, which are sometimes found in file paths.

const filePath = "/test/test1//2slashes/1slash/tab/..";
console.log(path.normalize(filePath));
// Output: '/test/test1/2slashes/1slash'

Joining Paths

The path.join() method can be used to combine multiple paths together. This method also resolves the correct path separators for the current operating system.

console.log(path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'));
// Output: '/foo/bar/baz/asdf'

Resolving Paths

The path.resolve() method returns an absolute path. It processes the path from right to left, prepending each part until an absolute path is created.

console.log(path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'));
// Output: '/tmp/subfile'

Getting Relative Paths

The path.relative() method returns a relative path from the first provided path to the second.

console.log(path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'));
// Output: '../../impl/bbb'

Getting the File Path Directory Name

The path.dirname() method returns the directory name of a file path.

console.log(path.dirname('/foo/bar/baz/asdf/quux'));
// Output: '/foo/bar/baz/asdf'

Getting the File Path Base Name

The path.basename() method returns the last part of a file path.

console.log(path.basename('/foo/bar/baz/asdf/quux.html'));
// Output: 'quux.html'

Getting the File Path Extension

The path.extname() method returns the extension of the file from a file path.

console.log(path.extname('index.html'));
// Output: '.html'

These are the basics of working with file paths in Node.js. Understanding these methods will help you manipulate file paths and directories effectively in your applications. Practice using these methods in different scenarios to get a better understanding of how they work.