【问题标题】:Meteor.js, Saving document to fileMeteor.js,将文档保存到文件
【发布时间】:2017-10-02 18:07:49
【问题描述】:

我正在尝试将文档保存到文件中,但似乎没有任何效果:

客户:

AutoForm.hooks({
updateProjectForm:{
    onSuccess: function(){
        var json = JSON.stringify(thisProject, null, 2);
        console.log('saveUpdatedDoc client')
        Meteor.call('saveUpdatedDoc', thisProject._id, json);

        thisProject = null;
        //FlowRouter.go('/Projects/');
    }
  }
});

服务器:

Meteor.methods({
saveUpdatedDoc: function(projectDataArray, json){
    console.log(console.log('saveUpdatedDoc server'));
    var fs = Meteor.npmRequire('fs');
    var projId = projectDataArray;
    var json = json;
    console.log(projId);
    console.log(json);
    //console.log(fs);
    // fs.writeFile("/files/" + projName, json, function(err) {
    //  if(err) {
    //      return console.log(err);
    //  }
    //  console.log("The file was saved!");
    // });
}
}); 

你现在可以看到它在 Meteor.npmRequire('fs');但是我尝试了许多其他方法,例如 Npm.require('fs') 和 Meteor.require('fs') 并在所有方法上都获得 Meteor 异常:

例如: 在 Meteor.npmRequire('fs') 我得到 TypeError: Meteor.npmRequire is not a function 在 Npm.require('fs');获取 ReferenceError:未定义 Npm 在需要('fs');出现错误:找不到模块“fs”,如果我尝试导入 fs(从“fs”导入 fs),那么所有应用程序在启动时都会崩溃。

我不知道该怎么做,我只需要保存一个文件,以便其他未连接到流星的进程可以读取 json 文件并使用它,但甚至不能做这个简单的事情......

packages.js 包含:

accounts-ui@1.1.9
accounts-password@1.4.0
aldeed:collection2-core
aldeed:autoform
check@1.2.5
dburles:collection-helpers
erasaur:meteor-lodash
fortawesome:fontawesome
fastclick
gwendall:auth-client-callbacks
kadira:flow-router
kadira:blaze-layout
matb33:bootstrap-glyphicons
raix:handlebar-helpers
spiderable
stolinski:stylus-multi
zimme:active-route
meteortoys:allthings
meteorhacks:npm

我真的被困在这个...它应该很简单... 10 倍

【问题讨论】:

    标签: node.js meteor


    【解决方案1】:

    就像需要 fs 一样简单,它内置在 node 中,因此不需要安装包,但它只能发生在服务器上,因为 fs 在客户端上不可用,或者如果是,将报错。

    所以在服务器方法中,如果你有一些 json 被传递,你可以这样做:

      const fs = require('fs')
      Meteor.methods({
        if (Meteor.isServer)    
          saveMyJson(jsonData) {
            fs.WriteFile('/path/to/file.json',JSON.stringify(jsonData,null,2) , 
              (err) => {
                 if (err) throw err;
                   console.log('Saved '+outfile);
            });
          }
        })
    

    在您的桌面上进行原型设计时可以这样做,但请记住,当您部署到 docker 实例时,文件系统将是只读的,因此您将无法执行此操作。

    【讨论】:

    • 这会引发异常:找不到模块 'fs' .... 所以仍然无法正常工作
    • 你的代码有严重的错误,还有错别字。它甚至不会编译。
    • 修复了代码。你正在运行什么版本的流星和节点? fs 是 node 的内置部分,afaik 一直存在
    • Meteor.methods) { 仍然无法编译 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 2012-04-18
    • 2019-08-29
    相关资源
    最近更新 更多