-1

There are a lot of solutions that are based on the fetch api or the XMLHttpRequest, but they return CORS or same-origin-policy errors.

The File/Filereader API works out of the box , but only for files chosen by the user via a input file (because that is the only way to import them as a File obj)

Is there a way to do something simple and minimal like

const myfile = new File('relative/path/to/file') //just use a path
const fr = new FileReader();
fr.readAsText(myfile);

Thanks

codebot
  • 517
  • 8
  • 29
  • 55
  • 3
    The browser isn't allowed to read directly from local files, it has to go through the file dialogue. Otherwise, web sites could read your files without you knowing it. – Barmar Nov 15 '21 at 22:55
  • 1
    `//just use a path` What is that path relative to? The user's home directory? The web application's home directory? You can't use the former because that opens up a whole can of security worms on the client side. You can't use the latter because that opens up a whole can of security worms on the server side. – Heretic Monkey Nov 15 '21 at 22:56
  • @HereticMonkey thank you for the info. So either by use input or files served by server – codebot Nov 16 '21 at 14:02

1 Answers1

-5

Try the following JS, this will use fs to read the file and if it exists it will turn it into a string and output to console. You can change it up to however you'd like.

var fs = require('fs');

fs.readFile('test.txt', 'utf8', function(err, data) {
    if (err) {
        return console.log(err);
    }
    console.log(data);
});
  • 2
    The OP is using the File API in the browser, not NodeJS. If they were using NodeJS, we already have many answers for that question. – Heretic Monkey Nov 15 '21 at 23:00