吾知网

标题: egret微信小游戏在本地用户文件目录下创建文件并读取内容 [打印本页]

作者: jekeyhui99    时间: 2018-10-23 18:39
标题: egret微信小游戏在本地用户文件目录下创建文件并读取内容

微信API参考


Platform.ts添加


declare interface Platform {

 

    getUserInfo(): Promise<any>;

 

    login(): Promise<any>

 

    getFileData(fileName): Promise<any>;

 

    writeFileData(fileName,data): Promise<any>;

}

 

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');

    })

  }

 

--------------------- 

作者:M硕 

来源:CSDN 

原文:https://blog.csdn.net/qq_39194398/article/details/81093158 

版权声明:本文为博主原创文章,转载请附上博文链接!






欢迎光临 吾知网 (http://175999.com/bbs/) Powered by Discuz! X3.2