DEV Community 👩‍💻👨‍💻

Paul Rumkin
Paul Rumkin

Posted on • Updated on

Trick how to replace path module with URL for path resolution

This is a tiny trick which could be useful when you need to resolve paths and make it in a crossplatform way. This code has no dependencies what makes its' usage extremely simple and cheap. Also such code could migrate from Node.js to a browser without dependencies bundling: no browserify, rollup or whatever is needed.

The trick is in using file: protocol in URL constructor.

Well, let's take an example:

const path = require('path')

const absPath = path.resolve('/some/root', '../index.js')

And replace it with:

const absPath = new URL('../index.js', 'file:///some/root/').pathname

In both cases we receive the same absPath value:


Note that built-in fs module accepts URLs as paths. Thus in cases when you need to use resolved path within the module, it's possible to just use a URL as argument:

const absPath = new URL('../../hello.txt', 'file:///project/root/')

fs.writeFileSync(absPath, 'Hello, World!')

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now