A file named status #7 at 50%.txt is unremarkable to a filesystem, but # starts a fragment in a URL and % starts an escape. Treating the filename as URL syntax can silently point somewhere else. In Node.js, convert native filenames with pathToFileURL and convert file URLs back with fileURLToPath. Use new URL to resolve URL references once you are already working in URL space.
Try a path without creating a file
Use Node.js 24 LTS or a newer supported Node.js release. Save as paths.mjs and run node paths.mjs from any working directory. The program constructs paths but does not write or read the named files.
import assert from 'node:assert/strict';
import { join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const name = 'status #7 at 50%.txt';
const file = resolve(name);
const url = pathToFileURL(file);
assert.ok(url.href.endsWith('/status%20%237%20at%2050%25.txt'));
assert.equal(fileURLToPath(url), file);
assert.equal(url.hash, '');
assert.equal(fileURLToPath(new URL('side%20note.txt', url)),
join(resolve('.'), 'side note.txt'));
assert.throws(() => fileURLToPath(new URL('https://example.org/')));
assert.throws(() => fileURLToPath(new URL('file:///a%2Fb')));
console.log(url.href.split('/').at(-1));
console.log('round trip OK');Expected output
status%20%237%20at%2050%25.txt
round trip OKThe encoded hash appears as %23 and does not become a fragment. The percent sign appears as %25. The sibling reference is already written as URL syntax and replaces the last component of the base file URL. Be deliberate about the base’s trailing slash when using a directory URL, since URL resolution otherwise treats its last component as a file component.
Debug the representation boundary
A native path and a serialized file URL are not interchangeable strings. Do not pass the URL’s pathname to an API expecting a decoded native filename. It may include percent escapes and does not account for native path differences such as Windows drive prefixes. For module-relative assets, resolve against import.meta.url instead of assuming the process was launched from the module’s directory. Convert only when the next interface actually needs a path.
If you see a literal %20 in a file-not-found message, check if URL syntax crossed into the filesystem layer. If a file URL contains an encoded slash, do not try to repair it with manual string replacement. The example also rejects a non-file scheme. Conversion checks syntax and representation, not whether a file exists or whether a caller is allowed to access it.
References and related reading: Node.js URL conversion documentation and Java Samples node.js tutorials.