Home > Blockchain >  Fetch local files with Node.js
Fetch local files with Node.js

Time:12-13

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

[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)

CodePudding user response:

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.

  • Related