通过角度读取/写入电子中的本地json文件

Jim*_*Jim 3 electron angular

我要创造getpostput在电子功能的访问本地JSON文件。

  1. 目前,我正在json-server这样做,但在运行电子项目之前,我每次都需要单独运行本地主机。

  2. 我使用了另一个名为 - 的库electron-json-storage。但我总是收到 fs 错误。

有没有办法解决这个问题,或者有没有其他有用的方法来做到这一点?

Pen*_*gyy 5

electron使用chromium和运行node.js,可以直接使用fs(node.js 内置文件系统模块)来操作本地文件。

例如,您可以将fs模块作为全局变量包含window在您的index.html(来自 angular 项目)

window.fs = require('fs')
Run Code Online (Sandbox Code Playgroud)

并建立为您的文件服务getpost以及post功能或基于来自API的任何人fs通过window.fs

读取本地文件例如:

@Injectable()
export class FileService {
  fs: any;
  constructor() {
    // or this.fs = <any>window.fs
    this.fs = (window as any).fs;
  }

  // read file synchronous
  getFile(path: string) {
    // return synchronous filestream
    return this.fs.readFileSync(path);
  }
}
Run Code Online (Sandbox Code Playgroud)