fs.writeFile不解析

问题描述 投票:0回答:1

我试图在Electron应用程序中用fs将画布中的图像保存到磁盘上的文件中。我使用asyncawait,但是当函数被调用时,我看到文件被创建,但是没有数据写入,直到我刷新页面。这一行 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个回答
0
投票

你可以试试这个。

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);
© www.soinside.com 2019 - 2024. All rights reserved.