Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetch local files with Node.js

In a browser environment fetching a local file is quite trivial: one just need to start a server (using MAMP, XAMP, Mac’s Python server, etc…), and then doing:

fetch("./foo.txt").then(etc...)

However, in Node.js this simple task has been a challenge. I’ve tried the same snippet using Node 18 (which comes with an experimental fetch API), but I’m always getting an invalid URL error:

TypeError: Failed to parse URL from foo.bar

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[cause]: TypeError [ERR_INVALID_URL]: Invalid URL

I’ve tried installing node-fetch, but I’m getting the same error. I could start a local server for node like http-server, but it tells me to go to http://localhost:8080 to see the server, that is, using the browser, but the issue is that I can do that without node, using only a node build is the whole point.

My question is: is it possible to fetch a local file in a node build (Sublime Text, VS Code etc…), without using a browser? (note: I can do it with fs, but in my question I’d like to discuss fetch only)

>Solution :

My question is: is it possible to fetch a local file in a node build (Sublime Text, VS Code etc…), without using a browser? (note: I can do it with fs, but in my question I’d like to discuss fetch only)

The Node.js implementation of fetch does not currently support file: scheme URLs…


fetch("file:///tmp/123").then(r => r.text()).then(d => console.log(d));

reports:

Error: not implemented… yet…


…nor (it appears) does it resolve a relative path to a file: scheme URI.

You should use the fs module.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading