使用JavaScript在本地应用程序(无服务器)中读取/写入和存储数据

问题描述 投票:0回答:1

所以我使用Javascript,React和Electron制作本地应用程序,我希望它能够在没有互联网的情况下正常工作。

我不能使用'localStorage',因为如果用户删除缓存,数据可能会被删除。

我尝试使用不同的模块进行读/写,其中没有一个主要是因为CORS。使用XMLHTTPrequest和Ajax也不起作用,并且时间不多了。

当我在测试服务器上使用它们时,它们返回主页的index.html(它们至少可以访问...但仍然无法读取数据)但是当我在构建中尝试它时,我得到了CORS错误。

我现在的想法是在我的网页上启用CORS,因为我不担心安全问题:应用程序将仅在线下运行,因此没有危险。但经过几个小时......我没有找到解决方案在客户端做到这一点。

如果有人有想法或建议,我将不胜感激。

我试过:fs,FileReader,FileSaver,$ .ajax,XMLHTTPrequests

 //using $ajax
 var test = $.ajax({
        crossDomain:true,
        type: 'GET',
        url:'../data/DefaultCategorie.txt',
        contentType: 'text/plain',
        success: function(data){
            console.log(data);
        },
        error: function(){
            alert('failed');
        },

    })

 //using fs
 fs.readFile('../data/DefaultCategorie.txt', 'utf8', (err, data) => {
        if (err) {
            console.log("Failed");
            throw err
        }
        console.log(data);
        fs.close(data, (err) => {
          if (err) throw err;
        });
      });
javascript jquery ajax electron offline
1个回答
0
投票

本文介绍了存储用户数据的3种最常用方法:How to store user data in Electron

Electron APIappDatadoes你想要什么。这是非常容易使用。

从上面的文章:

const userDataPath = (electron.app || electron.remote.app).getPath('userData');
this.path = path.join(userDataPath, opts.configName + '.json')
this.data = parseDataFile(this.path, opts.defaults);   

function parseDataFile(filePath, defaults) {

  try {
    return JSON.parse(fs.readFileSync(filePath));
  } catch(error) {
    // if there was some kind of error, return the passed in defaults instead.
    return defaults;
  }
}

文件

app.getPath(名称)

name String

返回String - 指向与name关联的特殊目录或文件的路径。失败时,抛出错误。

您可以通过名称请求以下路径:

appData - Per-user application data directory, which by default points to:
    %APPDATA% on Windows
    $XDG_CONFIG_HOME or ~/.config on Linux
    ~/Library/Application Support on macOS

userData - The directory for storing your app's configuration files,
which by default it is the appData directory appended with your app's
name.
© www.soinside.com 2019 - 2024. All rights reserved.