How can I read a file from a path, in Javascript?

9k Views Asked by At

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

1

There are 1 best solutions below

1
Diego LeBaron On

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