5

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

4
  • You are looking for the FileReader: developer.mozilla.org/en-US/docs/Web/API/FileReader Commented Aug 30, 2017 at 6:24
  • can you tell me an exact equivalent? I am little confused @GetOffMyLawn Commented Aug 30, 2017 at 6:29
  • There is no* fs equivalent in web APIs, for obvious security reasons. fs-> filesystem, 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...) Commented Aug 30, 2017 at 7:41
  • @Kaiido . Can you post that as an answer? I will close this question. Commented Oct 30, 2017 at 5:25

2 Answers 2

2

There is no* fs equivalent in web APIs, for obvious security reasons.

fs -> filesystem, 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 compared to fs either...)

Sign up to request clarification or add additional context in comments.

Comments

-2

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'>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.