meteor js how to write a file to disk from the server

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'

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

  1. Any ideas what is going wrong?
  2. Is it possible to obtain the absolute path to the meteor projects directory?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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('.');

You can also check if your folder exists :

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

Hope it will help you

Solution 2

If you are just looking for the absolute path for your app, you could simply do var base = process.env.PWD, which yields: /Users/[username]/[app-name]

This would avoid the extra stuff .meteor/local/build/programs/server

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply