egret微信小游戏在本地用户文件目录下创建文件并读取内容

微信API参考

Platform.ts添加

declare interface Platform {

    getUserInfo(): Promise;

    login(): Promise

    getFileData(fileName): Promise;

    writeFileData(fileName,data): Promise;
}

class DebugPlatform implements Platform {
    async getUserInfo() {
        return { nickName: "username" }
    }
    async login() {

    }
    /**获得文件内容 */
    async getFileData(fileName) {
        return { key: "key" }
    }
    /**文件中写入 */
    async writeFileData(fileName,data) {

    }
}

使用

 private async getFileData() {
        console.log("读取");
        let fileName = "score.txt";
        let d = await platform.getFileData(fileName);
        console.log(d);
    }
    private async writeFileData() {
        let fileName = "score.txt";
        let num = ~~(Math.random() * 100);
        console.log("写入,内容是" + num);
        await platform.writeFileData(fileName, num);
    }

发布的微信项目中platform.js添加

fs = wx.getFileSystemManager()
  getFileData(filePath) {
    var self = this;
    return new Promise((resolve, reject) => {
      self.fs.readFile({
        filePath: `${wx.env.USER_DATA_PATH}/` + filePath,
        encoding: "utf8",
        success: (data) => {
          resolve(data.data);
        },
        fail: (errMsg) => {
          console.log(errMsg);
          self.fs.writeFileSync(`${wx.env.USER_DATA_PATH}/` + filePath, '0', 'utf8');
        },
        complete: () => { console.log("读取完成") }
      });
    })
  }
  writeFileData(fileName, num) {
    var self = this;
    return new Promise((resolve, reject) => {
      self.fs.writeFileSync(`${wx.env.USER_DATA_PATH}/` + fileName, num , 'utf8');
    })
  }

 

你可能感兴趣的:(egret微信小游戏在本地用户文件目录下创建文件并读取内容)