Firefox WebExtensions, get local files content by path

后端 未结 1 1737
野的像风
野的像风 2021-01-02 02:00

I\'m trying to write a small add-on for firefox using the WebExtensions structure.

This add-on should read a local file content by it\'s absolute path:
\"/

相关标签:
1条回答
  • 2021-01-02 02:35

    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 );
        });
    
    0 讨论(0)
提交回复
热议问题