Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท path, os and url

Node.js url.fileURLToPath() method

Reference for url.fileURLToPath() in Node.js: convert file: URLs and import.meta.url to file system paths, with encoding rules, errors and Windows notes.

fileURLToPath(url) converts a file: URL (a string or a URL object) into an absolute file system path. It decodes percent-encoded characters and returns the path in the style of the current platform: forward slashes on POSIX, drive letters and backslashes on Windows.

Its most common use is turning import.meta.url into a file path in ES modules, which have no __filename. Do not convert by hand with url.pathname: that leaves percent-escapes in place and produces wrong paths on Windows.

NODE
import { fileURLToPath } from "node:url";

const file = fileURLToPath(import.meta.url);

Try it

Node.js Decoding file URLs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Errors and import.meta.url

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
url.fileURLToPath(url: string | URL, options?: { windows?: boolean }): string
Name Description
url A file: URL as a string or URL object.
options.windows true forces Windows path rules, false forces POSIX rules. The default follows the current platform.

Returns: an absolute path string.

Errors: TypeError [ERR_INVALID_URL_SCHEME] if the protocol is not file:. TypeError [ERR_INVALID_FILE_URL_HOST] for a non-empty host on POSIX (file://host/...). TypeError [ERR_INVALID_FILE_URL_PATH] when the path contains an encoded slash (%2F) on POSIX or an invalid drive on Windows.

Usage notes

  • Use it for import.meta.url. A typical pattern is path.dirname(fileURLToPath(import.meta.url)) as a stand-in for __dirname. Newer versions also offer import.meta.dirname and import.meta.filename.
  • Windows UNC paths: file://server/share/file.txt becomes \\server\share\file.txt on Windows and is an error on POSIX.
  • options.windows lets you test both conversions on one machine.
  • Query strings and fragments are ignored (file:///a.txt?x#y gives /a.txt).
  • The reverse conversion is pathToFileURL(). Together they round-trip safely.
  • fs functions accept URL objects directly, so conversion is only needed for string-based APIs and for logging.