readFileSync not reading URL as file

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//).

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

Solution 2

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply