DEV Community

Paul Rumkin
Paul Rumkin

Posted on • Edited on

2 2

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!')

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️