首页 > 解决方案 > 在 Meteor Server 上使用 fs 会在前端引发错误……但调用会在后端执行它应该执行的操作……为什么?

问题描述

我想 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.jsmeteorfs

解决方案


出于乐观的原因,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


推荐阅读