当我按下"保存"按钮来存储我的API密钥时,JSON文件通过将其从文件中删除而不是干扰它来替换我现有的Steam64ID.任何帮助都会得到重视.

//Save API Key to JSON
saveapi.addEventListener('click', () => {
  const apiKey = apibox.value;
  const data = { apikey: apiKey };
  const jsonStr = JSON.stringify(data, null, 2);
  window.electronAPI.writeFile(jsonStr);
});

//Save Steam64 ID to JSON
savesteam64.addEventListener('click', () => {
  const steam64id = steam64box.value;
  const data = { steam64id: steam64id };
  const jsonStr = JSON.stringify(data, null, 2);
  window.electronAPI.writeFile(jsonStr);
});

{
  "apikey": ""
  "steam64id": "" //This gets removed when I try save the api key
}

推荐答案

您遇到的问题是因为每次保存API密钥或Steam64ID时,您都会使用仅包含其中一个属性的新对象重新创建整个JSON文件.要保留JSON文件中的现有数据,您需要首先读取文件的当前内容,更新相关属性,然后将修改后的对象写回文件.

以下是修改事件侦听器以实现此目的的方法:

// Function to read the current JSON data, update it, and write it back
function updateJsonData(updateKey, updateValue) {
  window.electronAPI.readFile((err, data) => {
    if (err) {
      console.error('Error reading file:', err);
      return;
    }
    
    // Parse the existing JSON, or create a new object if the file is empty
    let jsonData = data ? JSON.parse(data) : {};
    
    // Update the specific key with the new value
    jsonData[updateKey] = updateValue;

    // Write the updated JSON back to the file
    const jsonStr = JSON.stringify(jsonData, null, 2);
    window.electronAPI.writeFile(jsonStr);
  });
}

// Save API Key to JSON
saveapi.addEventListener('click', () => {
  const apiKey = apibox.value;
  updateJsonData('apikey', apiKey);
});

// Save Steam64 ID to JSON
savesteam64.addEventListener('click', () => {
  const steam64id = steam64box.value;
  updateJsonData('steam64id', steam64id);
});

在这段代码中,updateJsonData是一个新函数,它处理读取现有的JSON文件,使用apikey或steam64id的新值更新它,然后将更新后的JSON写回文件.这种方法可以确保您保持现有数据的完整性,同时只更新JSON的必要部分.

注意:请确保您的Electron API.Read文件和Electron API.WriteFile函数已设置为正确处理读取和写入过程,包括错误处理.提供的代码假定实现这些函数是为了处理它们各自的任务.

Javascript相关问答推荐

如何通过onClick为一组按钮分配功能;

JS、C++和C#给出不同的Base 64 Guid编码结果

node TS:JWT令牌签名以验证客户端和后台问题之间的身份验证

了解Node.js中的EventEums和浏览器中的addEventEums之间的关系

在Angular中将样式应用于innerHTML

Angular 17—每当一个布尔变量变为真时触发循环轮询,只要它保持为真

虚拟滚动实现使向下滚动可滚动到末尾

如何将react—flanet map添加到remixjs应用程序

加载背景图像时同步旋转不显示的问题

rxjs插入延迟数据

覆盖加载器页面避免对页面上的元素进行操作

根据一个条件,如何从处理过的数组中移除一项并将其移动到另一个数组?

传递方法VS泛型对象VS事件特定对象

expo 联系人:如果联系人的状态被拒绝,则请求访问联系人的权限

在JS/TS中将复杂图形转换为数组或其他数据 struct

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

我在哪里添加过滤器值到这个函数?

我们是否可以在reactjs中创建多个同名的路由

相对于具有选定类的不同SVG组放置自定义工具提示

正在发出错误的URL请求