meteor js如何从服务器将文件写入磁盘 [英] meteor js how to write a file to disk from the server

查看:77
本文介绍了meteor js如何从服务器将文件写入磁盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个meteor包'myPackage',需要使用Npm FileSystem和Pah模块将文件写入磁盘。
该文件最终应该在example-app / packages / myPackage / auto_generated / myFile.js中,其中example-app project
添加了myPackage。

I am writing a meteor package 'myPackage' which needs to write a file onto disk using Npm FileSystem and Pah modules. The file should end up in the example-app/packages/myPackage/auto_generated/myFile.js, where example-app project has myPackage added.

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 ) ;
    },
} ); 

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

When I run the code above (server side only) I get

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

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

Note /Uses/martinfox/tmp/auto-generated folder does exist


  1. 任何想法出了什么问题?

  2. 是否有可能获得流星项目目录的绝对路径?


推荐答案

要获得项目的路径,您可以这样做:
from main存储在应用根目录中的.js

To get the path of your project you can do this : from main.js stored in the root of your app

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

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

You can also check if your folder exists :

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

希望它能帮到你

这篇关于meteor js如何从服务器将文件写入磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆