Meteorhacks npm best practice


#1

Hi, I am new to web development, Meteor and node and I’m trying to use the Meteor.npmRequire function. The examples shown in the official read me (https://github.com/meteorhacks/npm#readme) have the declaration of

var GithubApi = Meteor.npmRequire(‘github’);

inside a function, which is inside Meteor.methods in the server side code. If I need to use GithubApi multiple times across different server side functions, do I need to declare it like this every time, or is there somewhere that I can declare GithubApi globally on the server side and re-use it?

Any other tips on best practice on how to include/require node packages would be much appreciated.

Thanks for the help and apologies for the newbie question


Is Meteor up to date with the latest version of Node?
#2

If you want to make GithubApi a global, I would recommend to create a wrapper package for the npm package. This way, the global will be available in all your app files (= avoid load order problems). In this case you don’t need meteorhacks:npm. You can find an example of a wrapper package here: https://github.com/meteor-velocity/chokidar. If you do that your NPM package behaves like a Meteor package.

The other approach is to declare you dependencies as locally as possible. That means that you would do var GithubApi = Meteor.npmRequire('github'); in each file where you need it. You can put that statement on the top of the file if you use it in a lot of places. This approach is how you do it in Node.js and will do it with ES2015 modules.

Both works. I would suggest that you decide for one way and do it consistently throughout the app.


#3

You could put it in a package. Start by making a packages directory in your meteor project root

$ cd <your meteor base>
$ mkdir packages && cd packages
$ meteor create --package github-api
$ meteor add github-api  # adds your local package to your project
$ cd github-api

You’ll see a package.js file. You can essentially export a module to only the server pretty easily. Make a file like github-server. Then you can use Npm within it pretty easily.

Package.describe({
  name: 'github-api',
  description: 'quick example'
});

Package.onUse(function (api) {
  api.addFiles('github-server', 'server');
  api.export('Github');
});

Npm.depends({
  'github': '1.0.0'
});

Then you can just kinda make your module in your github-server.js file.

Github = {
  login: function (user, password) { },
  getRepo: function (access_token, repo) { }
}