I was trying to read and write a file in javascript. Nodejs 'fs'is not working. I came to know that there is an equivalent HTML5 API's.
What is the equivalent for
fs.writeFile('my.file', filedata)
fs.readFileSync(__dirname + '/dir/leaves.file')
in HTML5 filereader api
I was trying to read and write a file in javascript. Nodejs 'fs'is not working. I came to know that there is an equivalent HTML5 API's.
What is the equivalent for
fs.writeFile('my.file', filedata)
fs.readFileSync(__dirname + '/dir/leaves.file')
in HTML5 filereader api
fs
equivalent in web APIs, for obvious security reasons. fs
-> f
iles
ystem, and browsers won't give access to the user's filesystem to any random script on the web. You can read files with a FileReader, you can load files from a server with XHR, or you can ask your user to give you files from their f-s, and you can prompt your user to save files. But none of these operations will be done directly from the user's file-system, without his action. (*well actually we could consider IndexedDB and alike as filesystems...)
– Kaiido
Commented
Aug 30, 2017 at 7:41
There is no* fs
equivalent in web APIs, for obvious security reasons.
fs
-> f
iles
ystem, and browsers won't give access to the user's filesystem to any random script on the web.
But none of these operations will be done directly from the user's file-system, without his own action.
(*Actually we could consider IndexedDB and alike as filesystems, but they can't be pared to fs
either...)
You can load files using the FileReader like so:
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
<input type='file' accept='image/*' onchange='openFile(event)'><br>
<img id='output'>