【问题标题】:Using fs on Meteor Server throws error on frontend... but call does what it should on backend... Why?在 Meteor Server 上使用 fs 会在前端引发错误……但调用会在后端执行它应该执行的操作……为什么?
【发布时间】:2019-10-30 05:49:05
【问题描述】:

我想 1.从前端上传文件 2. 将数据发送到后端 3. 保存在服务器上的文件夹中

1 + 2 有效,3. 也有效,但有一些并发症...

在服务器上,imports/api/bills.js 中有以下代码,我从客户端调用 writefile 方法。 该文件确实已保存,并且我在服务器上没有收到任何错误,但我在客户端上确实收到了以下错误...

为什么会这样,我该如何解决?

我已经阅读了很多关于人们尝试在浏览器中使用 fs 的 stackoverflow 问题......但这不是我所做的(对吗?)

import {Meteor} from 'meteor/meteor';
import {Mongo} from 'meteor/mongo';
import {check} from 'meteor/check';

import { DateTime } from 'luxon';
import fs from "fs"


export const Bills = new Mongo.Collection('bills');


Meteor.methods({
   'bills.writefile' (blob) {
       fs.writeFile('/Users/mhe/Downloads/tax/binary.png', blob, function(err) {
           // If an error occurred, show it and return
           if(err) return console.error(err);
           // Successfully wrote binary contents to the file!
         });

    },

});

错误:


Exception while simulating the effect of invoking 'bills.writefile' TypeError: fs.writeFile is not a function
    at MethodInvocation.bills.writefile (bills.js:75)
    at livedata_connection.js:664
    at Meteor.EnvironmentVariable.EVp.withValue (meteor.js?hash=33066830ab46d87e2b249d2780805545e40ce9ba:1196)
    at Connection.apply (livedata_connection.js:653)
    at Connection.call (livedata_connection.js:556)
    at BillEntry.handleFile (BillEntry.js:88)
    at Object.BillEntry.handleForm [as onChange] (BillEntry.js:68)
    at onChange (FileControl.js:14)
    at HTMLUnknownElement.callCallback (modules.js?hash=9581e393779a85fee7aad573af1a251d5bed8130:4483)
    at Object.invokeGuardedCallbackDev (modules.js?hash=9581e393779a85fee7aad573af1a251d5bed8130:4533)

【问题讨论】:

    标签: node.js meteor fs


    【解决方案1】:

    出于乐观 UI 的原因,Meteor 在客户端模拟方法以快速返回值,并且仅在服务器表现不同时丢弃它们。在大多数情况下,这是您从未意识到的。

    但是你的情况是这样的。客户端模拟尝试调用客户端上不可用的 fs 并因此抛出。

    您可以通过在方法中使用isSimulation 来防止这种情况,以防止调用仅限服务器的导入。

    例子:

    Meteor.methods({
      'example' () {
        if (this.isSimulation) {
          return true // very optimistic
        } else {
           // original code
        }
      }
    })
    

    见:https://docs.meteor.com/api/methods.html#DDPCommon-MethodInvocation-isSimulation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 2016-09-22
      相关资源
      最近更新 更多