【问题标题】:fs.writeFile does not resolvefs.writeFile 无法解析
【发布时间】:2020-09-30 07:36:51
【问题描述】:

我正在尝试在 Electron 应用程序中使用 fs 将画布中的图像保存到磁盘上的文件中。我正在使用 async/await 但只要调用该函数,我就会看到文件已创建,但在刷新页面之前没有数据写入其中。 console.log('Saved') 行直到刷新才会执行。

import { promises as fs } from 'fs';
  async capture() {
    this.canvas = this.$refs.canvas;
    const context = this.canvas.getContext("2d").drawImage(this.video, 0, 0, 1280, 720);
    const image = canvas.toDataURL("image/png");


    const data = image.replace(/^data:image\/\w+;base64,/, "");
    const buf = Buffer.from(data, 'base64');
    try {

      await fs.writeFile(`${this.prescriptionId}.png`,buf);
      console.log('Saved')
    } catch (error) {
      console.log(error)
    }

  },

我不完全确定我做错了什么,有人可以帮忙吗?使用node v12.16.1 不会记录任何错误

更新: 如果我使用 fs.writeFileSync 我会得到一个错误:

TypeError: fs__WEBPACK_IMPORTED_MODULE_3__.promises.writeFileSync is not a function
    at VueComponent._callee4$ (MainPage.vue?23fd:369)
    at tryCatch (runtime.js?96cf:62)
    at Generator.invoke [as _invoke] (runtime.js?96cf:296)
    at Generator.prototype.<computed> [as next] (runtime.js?96cf:114)
    at step (asyncToGenerator.js?0f75:17)
    at eval (asyncToGenerator.js?0f75:35)
    at new Promise (<anonymous>)
    at new F (_export.js?63b6:36)
    at eval (asyncToGenerator.js?0f75:14)
    at VueComponent.capture (MainPage.vue?23fd:359)

【问题讨论】:

    标签: node.js vue.js electron fs electron-vue


    【解决方案1】:

    你可以试试这个。

    import { promises as fs } from 'fs';
    const context = 
    this.canvas.getContext("2d").drawImage(this.video, 0, 0, 1280, 720);
     const image = canvas.toDataURL("image/png");
    
    const data = image.replace(/^data:image\/\w+;base64,/, "");
    const buf = Buffer.from(data, 'base64');
     (async () => {
     try {
       await fs.writeFile(`${this.prescriptionId}.png`,buf);
     console.log('Saved')
     } catch (error) {
     console.log(error)
    }
    )(this);
    

    【讨论】:

    • 函数已经定义为async。我已经更新了问题
    • 问题是因为这个调用是异步的,并且可能在之后失去上下文,我能够通过使用同步执行它的 fs.writeFileSync 来修复它。希望这会有所帮助
    • 使用 fs.writeFileSync 给我一个错误。我已经更新了问题以包含它。即便如此,如果可能的话,我更愿意继续使用异步等待
    • 你可以试试这个browserify-fs
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2023-03-17
    • 2016-10-24
    相关资源
    最近更新 更多