meteor js如何从服务器将文件写入磁盘

mfo*_*fox 4 javascript node.js meteor

我正在编写一个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 ) ;
    },
} ); 
Run Code Online (Sandbox Code Playgroud)

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

Exception while invoking method 'autoGenerate' Error: ENOENT, 
no such file or directory '/Uses/martinfox/tmp/auto-generated/myFile.js'
Run Code Online (Sandbox Code Playgroud)

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

  1. 出了什么问题?
  2. 是否有可能获得流星项目目录的绝对路径?

Reb*_*lon 10

要获取项目的路径,您可以执行以下操作:从存储在应用程序根目录中的main.js

var fs = Npm.require('fs');
__ROOT_APP_PATH__ = fs.realpathSync('.');
console.log(__ROOT_APP_PATH__);
Run Code Online (Sandbox Code Playgroud)

您还可以检查您的文件夹是否存在:

if (!fs.existsSync(myPath)) {
    throw new Error(myPath + " does not exists");
}
Run Code Online (Sandbox Code Playgroud)

希望它会对你有所帮助