最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML5 FileReader equivalent for nodejs 'fs' - Stack Overflow

programmeradmin15浏览0评论

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

Share Improve this question asked Aug 30, 2017 at 6:23 SibirajSibiraj 4,7668 gold badges37 silver badges59 bronze badges 4
  • You are looking for the FileReader: developer.mozilla/en-US/docs/Web/API/FileReader – Get Off My Lawn Commented Aug 30, 2017 at 6:24
  • can you tell me an exact equivalent? I am little confused @GetOffMyLawn – Sibiraj 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...) – Kaiido Commented Aug 30, 2017 at 7:41
  • @Kaiido . Can you post that as an answer? I will close this question. – Sibiraj Commented Oct 30, 2017 at 5:25
Add a ment  | 

2 Answers 2

Reset to default 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.

  • 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 filesystem,
  • 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 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'>

发布评论

评论列表(0)

  1. 暂无评论