Javascript parse order in Meteor? (or) Server only methods?

Let’s say that I have a function that I want to call from multiple files server side:

var createFolder = function(path, mask, cb){

    var fs = Npm.require('fs');

    //Just creates a folder in server
}

Currently, I call this function in two different files of my Meteor application, both on the \server folder. The problem is, I have to declare the function in both files. Otherwise, the function is not yet defined when I call the functions in execution. If I can define the function only once in a different file, it will solve the issue. However, I currently do not know how and in what order the JS files are parsed when running Meteor. (Same question extends to knowing how Meteor parses CSS for the client).

One of the solutions I have in mind (other than the already implemented one of declaring the function twice) is to make it a Meteor method, and call is using Meteor.call('createFolder'...). But if I do that, the method can be called from the client, and that seems like a huge security liability.

What practice is best in this cases?

Thank you!

You’ll need to include the server file in such a way so that it gets loaded before it’s used.

There’s discussion of this load order here on the official docs. Specifically the load order section but the section as a whole is a good read.

If this isn’t an option or becomes too complex to manage you’ll need to packageify your application.

1 Like

server: Any directory named server is not loaded on the client. Similar to wrapping your code in if (Meteor.isServer) { ... }, except the client never even receives the code.

Hold on, would that not mean that if I declare a Meteor method on /server, I should not be able to call it from client? In my app, that is not at all the case.

Meteor methods are remote procedure calls essentially.

You send a string and some arguments down to the server and it responds. They don’t run or do anything on the client.

The only meteor method bit on the client is the Meteor.call etc functions.

They therefore only need to be defined in a server directory.

I’d advise against Meteor.isServer, in this case code is still sent to the client for no reason.

Load order may still have a bearing on your requirement. However, I suspect the main issue here is that the Meteor build process wraps each file into its own closure. Variables declared with var (as your createFolder is) end up inside the closure and so are nor visible to other files. What you need to do is remove the var, which tells the build process to put that variable into the server’s global space.