Using Node Modules with Meteor
After playing with Meteor for the past week or so, which overall I really enjoyed, the one thing that really bugged me was how to use node.js modules in a Meteor app. There are plenty of instructions out there that sort of tell you what to do, but I found all of them to be variously confusing and unclear. Of course, this isn't helped by the fact that at the time of writing Meteor is only version 0.6.5.1, so things are still in flux. The aim of this post is therefore to provide a comprehensive and clear guide to how I was able to get Meteor to work with Node modules.
The first thing of course is to initialise a new Meteor app. Feel free to skip this step if you're using an existing one.
meteor create myapp
cd myapp
Then create a folder called "packages" within the root of your app.
mkdir packages && cd packages
For each node module or custom package you want to use, create a new folder. For this example I'm going to use feedparser, as that's what I was using.
mkdir feedparser && cd feedparser
You'll then want to create two javascript files, one called package.js, and the other the name of the module.
touch package.js
touch feedparser.js
In package.js, declare the module you want to use, making sure to specify the version like so:
Package.describe({
summary: "Reads RSS feeds"
});
Npm.depends({feedparser: "0.16.1"});
Next, add the following lines, or the equivalent for your requirements, to package.js. You can find more information about what you can do here in the Meteor documentation, and by looking at the packages directory in the Meteor source tree. For me, these lines were what I required to access the module within my Meteor app.
Package.on_use(function(api){
api.add_files('feedparser.js', 'server');
if(api.export)
api.export('Feedparser');
});
Now, just create your variable to export by calling Npm.require()
on it in the other .js file you created.
Feedparser = Npm.require('feedparser');
Finally, in your application root folder, add the package to your app:
meteor add feedparser
Now Meteor will update the dependencies for the package. Once this is done, you should be able to use the module within your app by calling the api you exported.
var parser = Feedparser;
Hopefully now you'll have a working Node module within your Meteor app. You can view the full code for this example here. If you know a better or easier way to do this, or a more proper way, then please email me to say so.