Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/");
like image 900
Wanderer Avatar asked Feb 01 '17 14:02

Wanderer


People also ask

How do you create a new file in JavaScript?

We can create a file with the File constructor with JavaScript. For instance, we can write: const parts = [ new Blob(['you construct a file...'], { type: 'text/plain' }), ' Same way as you do with blob', new Uint16Array([33]) ]; const file = new File(parts, 'sample.

What is file object in JavaScript?

A File object is a specific kind of Blob , and can be used in any context that a Blob can. In particular, FileReader , URL. createObjectURL() , createImageBitmap() , and XMLHttpRequest. send() accept both Blob s and File s. See Using files from web applications for more information and examples.

Which files are JavaScript files?

JavaScript files have the file extension .js.


1 Answers

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");
like image 72
jmtalarn Avatar answered Oct 17 '22 17:10

jmtalarn