Firefox WebExtensions, get local files content by path

ε祈祈猫儿з 提交于 2019-11-29 03:55:05
Sabaz

I finally found the way to do this using the Fetch requests and FileReader APIs.

Here what I came up to:

function readFile(_path, _cb){

    fetch(_path, {mode:'same-origin'})   // <-- important

    .then(function(_res) {
        return _res.blob();
    })

    .then(function(_blob) {
        var reader = new FileReader();

        reader.addEventListener("loadend", function() {
            _cb(this.result);
        });

        reader.readAsText(_blob); 
    });
};

Using the example in my question this is how to use it:

readFile('file:///home/saba/desktop/test.txt', function(_res){

    console.log(_res); // <--  result (file content)

});

ES6 with promises

If you prefer to use Promises rather than callbacks:

let readFile = (_path) => {
    return new Promise((resolve, reject) => {
        fetch(_path, {mode:'same-origin'})
            .then(function(_res) {
                return _res.blob();
            })
            .then(function(_blob) {
                var reader = new FileReader();

                reader.addEventListener("loadend", function() {
                    resolve(this.result);
                });

                reader.readAsText(_blob);
            })
            .catch(error => {
                reject(error);
            });
    });
};

Using it:

readFile('file:///home/saba/desktop/test.txt')
    .then(_res => {
        console.log(_res); // <--  result (file content)
    })
    .catch(_error => {
        console.log(_error );
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!