meteorjs如何从服务器写入文件到磁盘

我写了一个meteor包“myPackage”,它需要使用Npm FileSystem和Pah模块将文件写入磁盘。 该文件应该在example-app / packages / myPackage / auto_generated / myFile.js中,其中example-app项目添加了myPackage。

fs = Npm.require( 'fs' ) ; path = Npm.require( 'path' ) ; Meteor.methods( { autoGenerate : function( script ) { var myPath = '/Users/martinfox/tmp/auto-generated' ; var filePath = path.join(myPath, 'myFile.js' ) ; console.log( filePath ) ; // shows /Uses/martinfox/tmp/auto-generated/myFile.js var buffer = new Buffer( script ) ; fs.writeFileSync( filePath, buffer ) ; }, } ); 

当我运行上面的代码(仅服务器端)我得到

 Exception while invoking method 'autoGenerate' Error: ENOENT, no such file or directory '/Uses/martinfox/tmp/auto-generated/myFile.js' 

注意/使用/ martinfox / tmp /自动生成的文件夹确实存在

  1. 任何想法出了什么问题?
  2. 是否有可能获得meteor项目目录的绝对path?

要获取项目的path,可以这样做:从存储在应用程序根目录下的main.js中获取

 var fs = Npm.require('fs'); __ROOT_APP_PATH__ = fs.realpathSync('.'); console.log(__ROOT_APP_PATH__); 

你也可以检查你的文件夹是否存在:

 if (!fs.existsSync(myPath)) { throw new Error(myPath + " does not exists"); } 

希望它会帮助你

如果你只是寻找你的应用程序的绝对path,你可以简单地做var base = process.env.PWD ,这产生: /Users/[username]/[app-name]

这将避免额外的东西。 .meteor/local/build/programs/server