Reputation: 13982
Using api/url and fs as in the guide:
const fs = require('fs');
let myURL = new URL('/ns/oa', 'https://www.w3.org/');
let contents = fs.readFileSync(myURL).toString();
console.log(contents)
ERROR: ERR_INVALID_URL_SCHEME
NOTE: this question is similar and good clue for readers (!), but it is not a solution to my problem, that was only to use URL as "real URL" (not collapsing the concept to file//
).
Upvotes: 4
Views: 17608
Reputation: 369
fs.readFile(Sync)
as well as all other fs
api only deals with local files.
URL
api can accept local files using the file://
protocol, and that's the meaning of using URL
in fs.readFile
.
If you need to get a file from the web you need to use http/https
api, specifically request
or similar to read the contents of the file/url you want. Something along this line:
const https = require('https');
let myURL = new URL('/ns/oa', 'https://www.w3.org/');
let body = [];
https.request(myURL, res=>{
// XXX verify HTTP 200 response
res.on('data', chunk=>body.push(chunk));
res.on('end', ()=>console.log(Buffer.concat(body).toString()));
}).end()
Upvotes: 3
Reputation: 6718
Just quoting the docs: Note the quotes in bold
URL object support Added in: v7.6.0
For most fs module functions, the path or filename argument may be passed as a WHATWG URL object. Only URL objects using the file: protocol are supported.
Simply put, https:
protocol is not supported
Example.
const fs = require('fs');
const fileUrl = new URL('file:///tmp/hello');
fs.readFileSync(fileUrl);
Upvotes: 9