在 Electron 中保存 JSON

2022-01-10 00:00:00 json electron javascript

我正在使用 Electron 构建一个应用程序.在这个应用程序中,我正在使用 JSON 构建数据结构.我的数据结构如下所示:

I am building an app using Electron. In this app, I am building a data structure using JSON. My data structure looks like this:

{
  items: [
    { id:1, name:'football' },
    { id:2, name:'soccer ball' },
    { id:3, name:'basketball' }
  ]
}

我想将此 JSON 保存到名为data.json"的文件中.我想将其保存到文件中,因为我想在下次应用程序启动时加载.我的挑战是,我不知道如何保存数据.事实上,我什至不确定应该将文件保存在 哪里.我是否将其保存在与应用程序相同的目录中?或者我应该使用一些跨平台的方法吗?

I want to save this JSON to a file called "data.json". I want to save it to a file because I want to load the next time the application starts. My challenge is, I do not know how to save the data. In fact, I'm not sure where I should even save the file. Do I save it in the same directory as the app? Or is there some cross-platform approach I should use?

目前,我有以下内容:

saveClick: function() {
  var json = JSON.stringify(this.data);
  // assume json matches the JSON provided above.
  // Now, I'm not sure how to actually save the file.
} 

那么,我如何/在哪里将 JSON 保存到本地文件系统以供以后使用?

So, how / where do I save JSON to the local file system for use at a later time?

推荐答案

Electron 缺乏一种简单的方法来持久化和读取应用程序的用户设置.electron-json-storage 实现了一个类似于 localStorage 的 API根据 app.getPath('userData') 的定义,在操作系统应用程序数据目录中写入和读取 JSON 对象.

Electron lacks an easy way to persist and read user settings for your application. electron-json-storage implements an API somehow similar to localStorage to write and read JSON objects to/from the operating system application data directory, as defined by app.getPath('userData').

相关文章