Search code examples
javascripthtmlfileapi

Can you create a Javascript File List or File object without html file input


I'm creating an offline javascript app that uses sql.js to load a sqlite database, add some filters and query the data and display various d3 based charts. However my users don't want to be bothered with the database stuff and having database file. I want to load file when the page loads.

<input id="inpLoadDB" type="file" onchange="loadDB()">

When I query that element it returns a FileList Object from which I can get the selected file. How can I build the FileList (or just the file object) without including the HTML element. Something like:

var fl=new FileList();
fl.readDir("./data/");

Solution

  • Accessing files from browser is restricted. If you're executing it from a browser it requires user interaction like upload file button. Even the File access api for HTML5 requires user to do something to get a file https://www.html5rocks.com/it/features/file_access

    Check this other answer on StackOverflow with an update for 2016 https://stackoverflow.com/a/372333/4635829

    You can access the filesystem programming with Javascript if you write a Node.js app and use the File I/O module

    var fs = require("fs");
    
    // Asynchronous read
    fs.readFile('input.txt', function (err, data) {
       if (err) {
          return console.error(err);
       }
       console.log("Asynchronous read: " + data.toString());
    });
    
    // Synchronous read
    var data = fs.readFileSync('input.txt');
    console.log("Synchronous read: " + data.toString());
    
    console.log("Program Ended");