Trick how to replace path module with URL for path resolution

rumkin

Paul Rumkin

Posted on May 9, 2019

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:

/some/index.js

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!')
💖 💪 🙅 🚩
rumkin
Paul Rumkin

Posted on May 9, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related