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.
import { fileURLToPath } from "node:url"; const file = fileURLToPath(import.meta.url);
Try it
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.
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
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 ispath.dirname(fileURLToPath(import.meta.url))as a stand-in for__dirname. Newer versions also offerimport.meta.dirnameandimport.meta.filename. - Windows UNC paths:
file://server/share/file.txtbecomes\\server\share\file.txton Windows and is an error on POSIX. options.windowslets you test both conversions on one machine.- Query strings and fragments are ignored (
file:///a.txt?x#ygives/a.txt). - The reverse conversion is
pathToFileURL(). Together they round-trip safely. - fs functions accept
URLobjects directly, so conversion is only needed for string-based APIs and for logging.